Sean Bannister
Sean Bannister

Reputation: 3185

Javascript - Having trouble using RegExp for a replace

I'm trying to do a Javascript replace (to remove some words from a string) but I require a variable to be used so I'm using new RegExp() as seen below however I can't figure out why the regular expression isn't replacing the words. When I use the same regex and don't use new RegExp() it works fine.

http://jsfiddle.net/HkEjB/

var string = "foo bar foo bar";

// With RegExp
var replace = "foo";
var regex = new RegExp("\b" + replace + " \b|\b " + replace + "\b|^" + replace + "$", 'igm');    
document.write(string.replace(regex, ""));

// Without RegExp
document.write('<br>');
document.write(string.replace(/\bfoo \b|\b foo\b|^foo$/igm, ''));

Upvotes: 0

Views: 73

Answers (1)

nachito
nachito

Reputation: 7035

You need to escape the backslashes: http://jsfiddle.net/HkEjB/1/

var string = "foo bar foo bar";

// With RegExp
var replace = "foo";

var regex = new RegExp("\\b" + replace + " \\b|\\b " + replace + "\\b|^" + replace + "$", 'igm');    
document.write(string.replace(regex, ""));

Upvotes: 2

Related Questions