I want to use str_replace
or its similar alternative to replace some text in JavaScript.
var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write("new_text");
should give
this is some sample text that i dont want to replace
If you are going to regex, what are the performance implications in comparison to the built in replacement methods.
If you don't want to use regex then you can use this function which will replace all in a string
Source Code:
How to use:
The code that others are giving you only replace one occurrence, while using regular expressions replaces them all (like @sorgit said). To replace all the "want" with "not want", us this code:
The variable "new_text" will result in being "this is some sample text that i dont want to replace".
To get a quick guide to regular expressions, go here:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
To learn more about
str.replace()
, go here:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
Good luck!
Not necessarily. see the Hans Kesting answer:
In JavaScript, you call the
replace
method on the String object, e.g."this is some sample text that i want to replace".replace("want", "dont want")
, which will return the replaced string.Added a method
replace_in_javascript
which will satisfy your requirement. Also found that you are writing a string"new_text"
indocument.write()
which is supposed to refer to a variablenew_text
.Using regex for string replacement is significantly slower than using a string replace.
As demonstrated on JSPerf, you can have different levels of efficiency for creating a regex, but all of them are significantly slower than a simple string replace. The regex is slower because:
For a simple test run on the JS perf page, I've documented some of the results:
The results for Chrome 68 are as follows:
From the sake of completeness of this answer (borrowing from the comments), it's worth mentioning that
.replace
only replaces the first instance of the matched character. Its only possible to replace all instances with//g
. The performance trade off and code elegance could be argued to be worse if replacing multiple instancesname.replace(' ', '_').replace(' ', '_').replace(' ', '_');
or worsewhile (name.includes(' ')) { name = name.replace(' ', '_') }