How to create a string "replace all"?

In every article or question I've seen quite a lot, just use:

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

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

So how do we do it right?


Input Example:

 'ab'.replaceAll('.','x') 

Required Conclusion:

 'axbx' 
+4
source share
5 answers

You can share 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"; 
+7
source

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

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

you can escape your yourvar variable using the following method:

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

XRegExp provides a function to escape 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
source

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); }; 

Decision 2

 'abc'.split('.').join('x'); 

jsPerf Test

0
source

Source: https://habr.com/ru/post/1400666/


All Articles