CyberJunkie
CyberJunkie

Reputation: 22674

Regex match string if not

I'm using regex to replace image source urls in an html file.

I want for example to replace img/ with <?= $folder ?>/img/

The issue: When I run the regex multiple times it will replace img/ again, creating:

<?= $folder ?>/<?= $folder ?>/img

..and so on. Is there a way to tell regex to replace img/ if not already <?= $folder ?>/img ?

I am trying /^(?:(?!<?= $folder ?>/img).)*$/ but not sure how to first match and check if that it doesn't already contain <?= $folder ?>/img

Upvotes: 0

Views: 91

Answers (2)

Jesse Paroz
Jesse Paroz

Reputation: 36

Try /(?!<\?= $folder \?>)img\//.

The bit at the beginning there, the (?!< ... ) is the notation for negative look-behind, that is, for checking if ... is earlier in the string. In this case, we're checking if the string
<\?= $folder \?> (note the escaped question marks) is earlier in the string. If that section is found earlier in a line with img/, it will be rejected, and won't match. So, each case of img/ will only be matched once.

This regex will fail for lines with more than one occurence of img/. There might be a way to allow for multiple occurences, but it would likely be a very long regex; and in my opinion, usually when a regex gets too long, it might be time to switch to a different tool.

Upvotes: 1

Quinn
Quinn

Reputation: 4504

If you prefer regex, please try:

function matchIfNot(str) {
  var newstr = str.replace(/^(?!(<\?=\s\$folder\s\?>\/))(img\/)/g, "<?= $folder ?>/img/")
  alert("Old string: " + str + "\nNew string: " + newstr)
}

matchIfNot("<?= $folder ?>/img/")
matchIfNot("img/")

Output:

Old string: <?= $folder ?>/img/
New string: <?= $folder ?>/img/

Old string: img/
New string: <?= $folder ?>/img/

Upvotes: 2

Related Questions