我需要替换句子中的单词。例如:
Programming makes my eyes grow tired. Eyes are cool.
我需要将第一次出现的单词“eyes”替换为单词“brain”,将第二次出现的单词“Eyes”替换为单词“Ears”。我想使用第一个单词Eyes的偏移量和第二个单词Eyes的偏移量。
我的代码:
suggestion.addEventListener('click', function() {
let offsetStart = parseInt(value[i]['offset']),
offsetEnd = parseInt(value[i]['offset']) + parseInt(value[i]['word'].length);
// VALUES: Programming makes my eyes grow tired. Eyes are cool.
const textarea = document.getElementsByTagName('textarea')[0].value;
// REPLACED VALUE: Programming makes my brain grow tired. Ears are cool.
});
2条答案
按热度按时间0h4hbjxa1#
toe950272#
这可以缩短为:
正则表达式的解释:
\b(eyes)\b
-捕获组1:带有单词边界的文字eyes
(这可以避免像eyesore
这样的误报(.*?)
-捕获组2:非贪婪扫描:\b(eyes)\b
-捕获组3:文字eyes
***了解有关regex的详细信息:***https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex