javascript - javascript - 一次替换多个文本
问题描述
我正在寻找一种简单快捷的方法来替换 javascript 中的多个字符串。
我目前的方法看起来像这样:
string.replace(string.replace(searchValue, newValue),newValue)
如果我必须替换文本中的 10 个字符串,那么这将非常大。是否有任何其他方法可用于替换 javascript 中的文本?
解决方案
split
,map
并且replace
应该为您工作:
const replaceString = (str, searchValue, newValue) => {
let replaceStr = str.split(" ").map(value => {
return value.replace(searchValue, newValue);
});
console.log(replaceStr.join(" ")); // Just for demo purpose, I am outputting the result to the console
};
const string = 'Hello world! How are you dear world?';
replaceString(string, 'world', 'earth');
推荐阅读
- javascript - ScrollMagic + TweenMax:同时绘制多个 SVG 路径?
- c++ - 调试可变参数
- vba - 用于数据验证的 VBA
- javascript - 如何更改 Bootstrap 本地化?
- python - 在 tf.nn.top_k 中加入 torch.topk 的 dim 参数
- authentication - 如何在 UserAuth 中编辑属性的 DataTypes
- python - 硬币槽树莓派的 Python 脚本
- javascript - SVG Circle:圆形裁剪图像
- javascript - 承诺一切不开火
- java - 关闭的 Google 广告横幅不再显示