How can I perform a str_replace in JavaScript, replacing text in JavaScript?

后端 未结 22 1890
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 00:29

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 re         


        
22条回答
  •  情书的邮戳
    2020-12-01 01:06

    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!

提交回复
热议问题