How can I perform a str_replace in JavaScript, rep

2020-01-29 04:05发布

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.

21条回答
Root(大扎)
2楼-- · 2020-01-29 04:19

If you don't want to use regex then you can use this function which will replace all in a string

Source Code:

function ReplaceAll(mystring, search_word, replace_with) 
{
    while (mystring.includes(search_word))
    {
        mystring = mystring.replace(search_word, replace_with);
    }

    return mystring;  
}

How to use:

var mystring = ReplaceAll("Test Test", "Test", "Hello"); 
查看更多
贪生不怕死
3楼-- · 2020-01-29 04:21

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:

var text = "this is some sample text that i want to replace";
var new_text = text.replace(/want/g, "dont want");
document.write(new_text);

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!

查看更多
The star\"
4楼-- · 2020-01-29 04:21

that function replaces only one occurrence.. if you need to replace multiple occurrences you should try this function: http://phpjs.org/functions/str_replace:527

Not necessarily. see the Hans Kesting answer:

city_name = city_name.replace(/ /gi,'_');
查看更多
看我几分像从前
5楼-- · 2020-01-29 04:22

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.

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want"); // new_text now stores the replaced string, leaving the original untouched
查看更多
做自己的国王
6楼-- · 2020-01-29 04:22

Added a method replace_in_javascript which will satisfy your requirement. Also found that you are writing a string "new_text" in document.write() which is supposed to refer to a variable new_text.

let replace_in_javascript= (replaceble, replaceTo, text) => {
  return text.replace(replaceble, replaceTo)
}

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

查看更多
做自己的国王
7楼-- · 2020-01-29 04:23

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:

Fixed-string matches don't have backtracking, compilation steps, ranges, character classes, or a host of other features that slow down the regular expression engine. There are certainly ways to optimize regex matches, but I think it's unlikely to beat indexing into a string in the common case.

For a simple test run on the JS perf page, I've documented some of the results:

<script>
// Setup
  var startString = "xxxxxxxxxabcxxxxxxabcxx";
  var endStringRegEx = undefined;
  var endStringString = undefined;
  var endStringRegExNewStr = undefined;
  var endStringRegExNew = undefined;
  var endStringStoredRegEx = undefined;      
  var re = new RegExp("abc", "g");
</script>

<script>
// Tests
  endStringRegEx = startString.replace(/abc/g, "def") // Regex
  endStringString = startString.replace("abc", "def", "g") // String
  endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String
  endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp
  endStringStoredRegEx = startString.replace(re, "def") // saved regex
</script>

The results for Chrome 68 are as follows:

String replace:    9,936,093 operations/sec
Saved regex:       5,725,506 operations/sec
Regex:             5,529,504 operations/sec
New Regex String:  3,571,180 operations/sec
New Regex:         3,224,919 operations/sec

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 instances name.replace(' ', '_').replace(' ', '_').replace(' ', '_'); or worse while (name.includes(' ')) { name = name.replace(' ', '_') }

查看更多
登录 后发表回答