如果在<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);
答案 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);