0

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, ''));

1 Answer 1

2

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

1 Comment

:) of course, I new it had to be something simple. thanks a heap.

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.