6

Every article or question I've seen pretty much says, just use:

str.replace(/yourstring/g, 'whatever');

But I want to use a variable in place of "yourstring". Then people say, just use new RegExp(yourvar, 'g'). The problem with that is that yourvar may contain special characters, and I don't want it to be treated like a regex.

So how do we do this properly?


Example input:

'a.b.'.replaceAll('.','x')

Desired output:

'axbx'
3
  • You want to not treat regex like regex? Can you define the types of input you'd like to provide? Will you want regex-functionality, or is it just a string of literal characters, "ABc34*\d/4h" you want to work with/replace? Commented Mar 9, 2012 at 21:53
  • @DavidThomas: Any input. All I want is a simple function that replaces all instances of "x" with "y", not just the first one, as string.replace does. Commented Mar 9, 2012 at 21:59
  • 1
    'a.b.c'.split('.').join('x') Commented Mar 9, 2012 at 22:14

5 Answers 5

10

You can split and join.

var str = "this is a string this is a string this is a string";

str = str.split('this').join('that');

str; // "that is a string that is a string that is a string";
Sign up to request clarification or add additional context in comments.

2 Comments

This solution seems to be significantly faster, so you get the check. Wouldn't have thought of doing this; thanks.
You made my day, thanks!
3

From http://cwestblog.com/2011/07/25/javascript-string-prototype-replaceall/

String.prototype.replaceAll = function(target, replacement) {
  return this.split(target).join(replacement);
};

Comments

1

you can escape your yourvar variable using the following method:

function escapeRegExp(text) {
    return text.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

1 Comment

I think you went a little excessive on the backslashes. When inside a character set, you don't need to escape much. Nevertheless, this is a viable solution. +1
1

XRegExp provides a function for escaping regular expression characters in strings:

var input = "$yourstring!";
var pattern = new RegExp(XRegExp.escape(input), "g");
console.log("This is $yourstring!".replace(pattern, "whatever"));
// logs "This is whatever"

1 Comment

I don't really want the whole library, so I dug through the source: nativ.replace.call(str, /[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); Library does look neat though.
1

Solution 1

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

String.prototype.replaceAll = function(search, replace) {
    return this.replace(new RegExp(RegExp.escape(search),'g'), replace);
};

Solution 2

'a.b.c.'.split('.').join('x');

jsPerf Test

Comments

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.