首页 > 解决方案 > javascript - 一次替换多个文本

问题描述

我正在寻找一种简单快捷的方法来替换 javascript 中的多个字符串。

我目前的方法看起来像这样:

string.replace(string.replace(searchValue, newValue),newValue)

如果我必须替换文本中的 10 个字符串,那么这将非常大。是否有任何其他方法可用于替换 javascript 中的文本?

标签: javascript

解决方案


splitmap并且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');


推荐阅读