How can I accomplish conditional replacement using JavaScript RegExp?
I am trying to wrap my head around using regex and replace () with JavaScript but not yet successfully
Suppose I have a line containing this:
<img alt="a picture of ..." src="image/1533?foo=1&bar=2$zot=3" width="500" />
If zot=3
, I want to remove foo (and its value) (or replace it with foo=x
an empty string).
The replacement will look like this:
<img alt="a picture of ..." src="picture/1533?bar=2$zot=3" width="500" />
I want it to be as bulletproof as possible since I can never be sure which order the URL parameters will be given.
Is this possible using a single regex or are there any better solutions?
I was thinking to use DOM and
- moving all nodes
img
- get attribute
src
- perform the checks if the value
@src
iszot=3
- if it has
zot=3
, replace withfoo=1
an empty string
Of course, I have to make sure that any ampersands etc. removed too.
But I hope to resolve it using a regex or two,
Thanks for any answers and advice!
var el = document.getElementsByTagName("img");
for(var i=0;i<el.length;i++)
{
if(el.src.match(/zot=3/))
el.src = el.src.replace(/(?<=[?&])foo=[^&]+&?/, '');
}
Untested - but should do what you are looking for.
Regular expression:
-
(?<=[?&])
- zero width looks behind - matches line starting after? or & -
foo=[^&]+
- match 'foo =' followed by any number of characters and characters. -
&?
- optionally matches a and if it exists
Replace the matched string with nothing to remove the parameter.
a source to share
What gnarf said, except that JavaScript does not support regex lookbehinds (at least my IE and FF implementations do not have JavaScript, or I copy and paste incorrectly), so I cannot verify this as being written without exception. So I broke the expression in two to handle different cases:
1), starting with?, And in this case? persists, but the following is not, and
2), starting with &, in this case the leading one is not saved, but the next one is.
While on it, I've removed the expectation that foo = will be followed by anything other than possibly a and the next parameter to run. Also note that there is little forgiveness for spaces.
el.src = el.src.replace(/(\?)foo=[^&]*&?|&foo=[^&]*(&?)/, '$1$2');
I tested it with these src lines:
"image/1533?foo=1&bar=2$zot=3"
"image/1533?foo=&bar=2$zot=3"
"image/1533?bar=2$zot=3&foo=1"
"image/1533?bar=2$zot=3&foo="
"image/1533?bar=2$zot=3&foo=1&another=123"
"image/1533?bar=2$zot=3&foo=&another=123"
And got the following results:
"image/1533?bar=2$zot=3"
"image/1533?bar=2$zot=3"
"image/1533?bar=2$zot=3"
"image/1533?bar=2$zot=3"
"image/1533?bar=2$zot=3&another=123"
"image/1533?bar=2$zot=3&another=123"
Good luck!
a source to share