JavaScript 是否有方法可以替换字符串的一部分而不创建新的字符串?
javascriptweb developmentobject oriented programming更新于 2025/11/6 9:16:17
是的,我们可以使用 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

