JavaScript是否具有替換部分字串但不建立新字串的方法?


是的,我們可以在不建立新字串的情況下使用如下所示的 replace() 方法替換部分字串 -

var anyVariableName=yourValue;
yourVariableName=yourVariableName.replace(yourOldValue,yourNewValue);

示例

var message="Hello,this is John";
console.log("Before replacing the message="+message);
message=message.replace("John","David Miller");
console.log("After replacing the message="+message);

要執行上述程式,你需要使用以下命令 -

node fileName.js.

此處,我的檔名是 demo57.js。

輸出

這將產生以下輸出 -

PS C:\Users\Amit\JavaScript-code> node demo57.js
Before replacing the message=Hello,this is John
After replacing the message=Hello,this is David Miller

更新於:2020 年 9 月 3 日

129 次瀏覽

啟動你的 職業生涯

完成課程獲取認證

開始學習
廣告