如何使用replace函数将mark标签连接到字符串中的单个单词?

时间:2019-02-18 02:45:23

标签: javascript

如果在<mark>数组中找到字符串,则以下函数尝试将knownWords标记连接到字符串的元素。因此,执行代码后,输出应该是

Marked string: The <mark>quick</mark> <mark>brown</mark> fox jumped over the <mark>lazy</mark> dog. 

但是,字符串在执行后保持不变。

let knownWords = ["quick", "brown", "lazy"];

let string = 'The quick brown fox jumped over the lazy dog.';

console.log('Original string:', string);
knownWords.forEach(match);

function match(value) {
  string.replace(/value/g, '<mark>' + value + '</mark>');

}
console.log('Marked string: ',string);

3 个答案:

答案 0 :(得分:5)

let knownWords = ["quick", "brown", "fox"];

let string = 'The quick brown fox jumped over the lazy dog.';

console.log('Original string:', string);
knownWords.forEach(match);

function match(value) {
  string.replace(/value/g, '<mellan>' + value + '</mellan>');

}
console.log('Marked string: ',string);

答案 1 :(得分:2)

string重新分配给string.replace()的结果,并使用RegExp构造函数,并将value作为参数传递,而不是RegExp文字{{1 }}

/value/

或者

let knownWords = ["quick", "brown", "lazy"];

let string = 'The quick brown fox jumped over the lazy dog.';

console.log('Original string:', string);
knownWords.forEach(match);

function match(value) {
  string = string.replace(new RegExp(`${value}`), '<mark>' + value + '</mark>');
}

console.log('Marked string: ', string);

答案 2 :(得分:2)

let string = 'The quick brown fox jumped over the lazy dog.';

let knownWords = ["quick", "brown", "fox"];

console.log('Original string:', string);
knownWords.forEach(match);

function match(value) {
  string.replace(/value/g, '<mark>' + value + '</mark>');

}
console.log('Marked string: ',string);