JavaScript字符串替换所有出现的数组值

6

我希望替换字符串中的所有出现,但问题在于我有一个要删除的单词数组和对应的删除值。

例如:

var string = "this is a string to replace. This string should be replaced using javascript";

var replaceArray = ["this","is","string","should","javascript"];

var replaceArrayValue = ["There","are","strings","have to","node.js"];

for (var i = replaceArray.length - 1; i >= 0; i--) {

    var finalAns = string.replace(replaceArray[i],replaceArrayValue[i]);
}

我希望能得到类似于以下内容的翻译:

There are strings to replace. There strings have to be replaced using node.js

我在这里找到了一些解决方案,其中最好的解决方案是这里。但我不能使用/string/g中的字符串,我必须使用replaceArray[i]


你可以这样写:var regex = new RegExp(replaceArray[i], 'g') - Rajesh
5个回答

5
如果您更喜欢调整方法,可以使用RegExp构造函数来构建带有变量的动态正则表达式,并确保只匹配用单词边界包围的整个单词。不要忘记转义字面模式,并在循环之前声明finalAns并用string变量内容初始化。

var string = "this is string to replace. this string should replace using javascript";
var replaceArray = ["this","is","string","should","javascript"];
var replaceArrayValue = ["There","are","strings","have to","node.js"];
var finalAns = string;
for (var i = replaceArray.length - 1; i >= 0; i--) {
    finalAns = finalAns.replace(RegExp("\\b" + replaceArray[i].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "\\b", "g"), replaceArrayValue[i]);
}
console.log(finalAns);

请注意,Roman的方法使用单个静态正则表达式似乎是当前任务中最有效的(无需每次动态构建正则表达式)。

如果要替换的单词中有美元符号($),你会如何处理? - ztalbot
@ztalbot 使用 replaceArrayValue[i].replace(/\$/g, '$$$$') - Wiktor Stribiżew
哇,你好快啊!我的原始问题无法编辑得够快。var string = "$this is string to replace. this string should replace using javascript"; var replaceArray = ["$this","is","string","should","javascript"]; var replaceArrayValue = ["#There","are","strings","have to","node.js"]; - ztalbot
找到解决方案了。我的原始字符串不同,我所要做的只是基本的 finalAns = finalAns.replace(replaceArray[i], replaceArrayValue[i]); - ztalbot

3
使用以下方法与replacement函数配合使用:

var string = "this is string to replace. this string should replace using javascript",
    replaced = string.replace(/\b\w+\b/g, function ($m) {
        var search = ["this","is","string","should","javascript"],
            replacement = ["There","are","strings","have to","node.js"],
            key = search.indexOf($m);

        return (key !== -1)? replacement[key] : $m;
    });

console.log(replaced);

来自 Nicholas Zakas 的《高性能 JavaScript》:

"... 关于超出作用域的变量: 将任何经常使用的超出作用域的变量存储在局部变量中,然后直接访问局部变量。"


1
这应该是官方答案,对我非常有效,在字符串中替换类名可以完美解决问题,而其他所有答案都会出现问题。 - Wazime

1

没有正则表达式

在循环中,只能设置变量 string = finalAns;。因为每次循环都会设置旧字符串,这样就会出现问题。

var string = "this is string to replace. this string should replace using javascript";

var replaceArray = ["this","is","string","should","javascript"];

var replaceArrayValue = ["There","are","strings","have to","node.js"];
alert(replaceArray.length);
for (var i = replaceArray.length - 1 ; i >= 0; i--) {

    var finalAns = string.replace(replaceArray[i],replaceArrayValue[i]);
    string =finalAns;
}
alert(finalAns);

代码片段示例

var string = "this is string to replace. this string should replace using javascript";

var replaceArray = ["this","is","string","should","javascript"];

var replaceArrayValue = ["There","are","strings","have to","node.js"];

for (var i = replaceArray.length - 1 ; i >= 0; i--) {

    var finalAns = string.replace(replaceArray[i],replaceArrayValue[i]);
    string =finalAns;
}
alert(finalAns);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


0

我使用声明式方法找到了一个解决方案:

const string = 'boo and Boo2'
const dictionary = { boo: 'faa', boo2: 'faa2' }
return string.split(' ')
  .map(word => dictionary[word.toLowerCase()] ?? word)
  .join(' ')
// 'faa and faa2'

0

format方法用于替换给定数组的所有出现次数。

formatAll方法用于将给定数组的顺序替换为所有首次出现的单词(这是问题中要求的)。

String.prototype.format = function (_key, _data) {
  return this.split(_key).map(function (value, index) { return _data[index] ? value + _data[index] : (value ? value : '') }).join("");
}

String.prototype.formatAll = function (_keys, _data) {
  let shift = () => { _keys.shift(); return _data.shift() }
  return this.split(/\s+/).map(function (value) { return value == _keys[0] ? shift() : value }).join(" ")
}

"path/of/0/object/s/0/feature".format(0, [10,22])
//outputs
'path/of/10/object/s/22/feature'

"this is a string to replace. This string should be replaced using javascript".formatAll(["this","is","string","should","javascript"],["There","are","strings","have to","node.js"])
//outputs
'There are a strings to replace. This string have to be replaced using node.js'

"Merhaba dünya! Merhaba ay!".formatAll(["Merhaba"], ["Hello"])
//outputs
'Hello dünya! Merhaba ay!'

"Merhaba dünya! Merhaba ay!".formatAll(["Merhaba", "Merhaba"], ["Hello", "Selam"])
//outputs
'Hello dünya! Selam ay!'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接