Home > front end >  Word substitution from offset x to y in JavaScript
Word substitution from offset x to y in JavaScript

Time:01-21

I need to replace a word from a sentence. For example:

Programming makes my eyes grow tired. Eyes are cool.

I need to replace the first occurrence of the word "eyes" with the word "brain" and the second occurrence of the word "Eyes" with the word "Ears". I want to use the offset of the first word Eyes and the offset of the second word Eyes.

My code:

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.

});

CodePudding user response:

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);

CodePudding user response:

This can be shortened to:

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);

Explanation of regex:

  • \b(eyes)\b -- capture group 1: literal eyes with word boundaries (this avoids false positives like eyesore
  • (.*?) -- capture group 2: non-greedy scan to:
  • \b(eyes)\b -- capture group 3: literal eyes

Learn more about regex: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex

  • Related