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.
hm.. Did you check replace() ?
Your code will look like this
All these methods don't modify original value, returns new strings.
Replaces 1st space with _
Replaces all spaces with _ using regex. If you need to use regex, then i recommend testing it with https://regex101.com/
Replaces all spaces with _ without regex. Functional way.
You have the following options:
More info -> here
There are already multiple answers using str.replace() (which is fair enough for this question) and
regex
but you can use combination of str.split() and join() together which is faster thanstr.replace()
andregex
.Below is working example:
In Javascript, replace function available to replace sub-string from given string with new one. Use:
You can even use regular expression with this function. For example, if want to replace all occurrences of
,
with.
.Here
g
modifier used to match globally all available matches.If you really want a equivalent to PHP's
str_replace
you can use Locutus. PHP's version ofstr_replace
support more option then what the JavaScriptString.prototype.replace
supports. For example tags:or array's
Also this doesn't use regex instead it uses for loops. If you not want to use regex but want simple string replace you can use something like this ( based on Locutus )
for more info see the source code https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js