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条回答
不美不萌又怎样
2楼-- · 2020-01-29 04:33
var new_text = text.replace("want", "dont want");
查看更多
Explosion°爆炸
3楼-- · 2020-01-29 04:34
function str_replace($old, $new, $text)
{
   return ($text+"").split($old).join($new); 
}

You do not need additional libraries.

查看更多
三岁会撩人
4楼-- · 2020-01-29 04:38

Use JS String.prototype.replace first argument should be Regex pattern or String and Second argument should be a String or function.

str.replace(regexp|substr, newSubStr|function);

Ex:

var str = 'this is some sample text that i want to replace'; var newstr = str.replace(/want/i, "dont't want"); document.write(newstr); // this is some sample text that i don't want to replace

查看更多
登录 后发表回答