Skip to content Skip to sidebar Skip to footer

Regular Expression - Match String Not Preceded By Another String (javascript)

I am trying to find a regular expression that will match a string when it's NOT preceded by another specific string (in my case, when it is NOT preceded by 'http://'). This is in J

Solution 1:

As JavaScript regex engines don't support 'lookbehind' assertions, it's not possible to do with plain regex. Still, there's a workaround, involving replace callback function:

var str = "As http://JavaScript regex engines don't support `lookbehind`, it's not possible to do with plain regex. Still, there's a workaround";

var adjusted = str.replace(/\S+/g, function(match) {
  return match.slice(0, 7) === 'http://'
    ? match
    : 'rocks'
});
console.log(adjusted);

You can actually create a generator for these functions:

var replaceIfNotPrecededBy = function(notPrecededBy, replacement) {
   returnfunction(match) {
     returnmatch.slice(0, notPrecededBy.length) === notPrecededBy
       ? match
       : replacement;
   }
};

... then use it in that replace instead:

var adjusted = str.replace(/\S+/g, replaceIfNotPrecededBy('http://', 'rocks'));

JS Fiddle.

Solution 2:

This also works:

var variable = 'http://www.example.com www.example.com';
alert(variable.replace(newRegExp('([^(http:\/\/)|(https:\/\/)])(www.example.com)','g'),'$1rocks'));

The alert says "http://www.example.com rocks".

Post a Comment for "Regular Expression - Match String Not Preceded By Another String (javascript)"