regex JavaScript中从偏移量x到y的单词替换

8tntrjer  于 2023-01-27  发布在  Java
关注(0)|答案(2)|浏览(99)

我需要替换句子中的单词。例如:

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.

});
0h4hbjxa

0h4hbjxa1#

let str = 'Programming makes my eyes grow tired. Eyes are cool.';
let res = str.replace(/^(.*?)eyes(.*?)eyes/i, 
            (_, g1, g2) => g1 + 'brain' + g2 + 'Ears');
console.log(res);
toe95027

toe950272#

这可以缩短为:

const input = 'Programming makes my eyes grow tired. Eyes are cool.';
let result = input.replace(/\b(eyes)\b(.*?)\b(eyes)\b/i, 'brain$2Ears');
console.log(result);

正则表达式的解释:

相关问题