纯javascript相当于jquery的replace()

pure javascript equivalent of jquery replace()

本文关键字:replace jquery javascript 相当于      更新时间:2023-09-26

在jquery中,我像这样使用替换

replace('old text','new text')

我如何用纯javascript做同样的事情?

这个纯Javascript。看到这里。

var str = "Visit Microsoft!";
var res = str.replace("Microsoft", "W3Schools");

replace是javascript中字符串对象的一个方法:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

你列出的语法是纯javascript,即

string.replace(regexp/substr,newstring)

可以使用

string.replace(regexp/substr,newstring)
为例:

<script type="text/javascript">
var str="Visit Microsoft!";
document.write(str.replace("Microsoft", "Stackoverflow"));
</script> 

使用JavaScript string.replace()

var str="fooz bard";
alert(str.replace("foo", "baz")); //bazz bard

返回一个新字符串,其中包含被替换的模式的部分或全部匹配。模式可以是字符串或RegExp,替换可以是每次匹配时调用的字符串或函数。

'string'.replace是原生javascript方法。可以直接用

console.log( 'string'.replace('ing', 'wow') ); // 'strwow'

如果你想用另一个dom元素替换一个元素,有一个简单的方法:

oldElem.parentNode.replaceChild(newElem, oldElem);