0

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

6
  • I don't know if it would be cleaner to look at, but you could first replace the full string with [PLACEHOLDER], then do your replace, then replace [PLACEHOLDER] with your full string again. I believe you can do your replace with just a single RegEx, but this way would be an alternative that's a little more linear. Commented Mar 4, 2016 at 15:20
  • @anubhava i have updated my question Commented Mar 4, 2016 at 15:28
  • Why are you using regex for this? You only need to do a find and replace. Commented Mar 4, 2016 at 15:36
  • @Mikey it is for a gulp component which uses regex Commented Mar 4, 2016 at 15:52
  • Your regex /^(?:(?!<?= $folder ?>\/img).)*$/ works fine and doesn't replace if same string is already there in input Commented Mar 4, 2016 at 16:04

2 Answers 2

2

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/
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Please elaborate on how this regex answers the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.