Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a string "replace all" function?

Tags:

javascript

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'
like image 788
mpen Avatar asked Mar 09 '12 21:03

mpen


People also ask

How do I replace all in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

Can you replace all occurrences?

To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')

What do replace all () do?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.


1 Answers

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";
like image 90
Marshall Avatar answered Oct 11 '22 19:10

Marshall