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.
You would use the
replace
method:The first argument is what you're looking for, obviously. It can also accept regular expressions.
Just remember that it does not change the original string. It only returns the new value.
You should write something like that :
JavaScript has
replace()
method of String object for replacing substrings. This method can have two arguments. The first argument can be a string or a regular expression pattern (regExp object) and the second argument can be a string or a function. An example ofreplace()
method having both string arguments is shown below.Note that if the first argument is the string, only the first occurrence of the substring is replaced as in the example above. To replace all occurrences of the substring you need to provide a regular expression with a
g
(global) flag. If you do not provide the global flag, only the first occurrence of the substring will be replaced even if you provide the regular expression as the first argument. So let's replace all occurrences ofone
in the above example.Note that you do not wrap the regular expression pattern in quotes which will make it a string not a regExp object. To do a case insensitive replacement you need to provide additional flag
i
which makes the pattern case-insensitive. In that case the above regular expression will be/one/gi
. Notice thei
flag added here.If the second argument has a function and if there is a match the function is passed with three arguments. The arguments the function gets are the match, position of the match and the original text. You need to return what that match should be replaced with. For example,
You can have more control over the replacement text using a function as the second argument.
Method to
replace substring in a sentence
using React:RunMethodHere
You can use
And to change multiple values in one string at once, for example to change # to string v and _ to string w:
More simply:
Replaces all spaces with '_'!