Working with substring. How can I change the text inside a string?

  • 0
    Write a replaceSubstring function that takes a string, words that contains two space-separated words, and a new substring, substring. The purpose of the function is to replace everything in string between the specified words with a new substring substring.

    Example:

    replaceSubstring ('I hate these robots', 'I robots', 'love these cute') // 'I love these cute robots'
    replaceSubstring ('I am a robot', 'I robot', 'dreamed of a') // 'I dreamed of a robot'

    I got to this step, then I got stuck.
    Please tell me how can I solve it further?

    function replaceSubstring(string, words, substring) {
    
        const newString = string.split(" ");
        const newWord = words.split(" ");
    
        for(let i = 0; i < newWord.length; i++){
          for(let j = 0; j < newString.length; j++){
            if(newWord[i] === newString[j]){
              newString[i].replace(newWord[i]);
            }
          }
        }
        console.log(newWord);
        console.log(newString);
    
    }
    JavaScript Anonymous, Feb 11, 2019

  • 2 Answers
  • 0
    Option with search string functions



    function replaceSubstring(string, words, substring) {
    // Получаем слова между которыми искать замену
    const [word1, word2] = words.split(' ')

    // Находим индексы этих слов
    const [pos1, pos2] = [string.indexOf(word1), string.indexOf(word2)]
    if (pos1 < 0 || pos1 + word1.length >= pos2) return string

    // Добавляем пробелы в строку замены, если отсутствуют
    if (!substring.startsWith(' ')) substring = ' ' + substring
    if (!substring.endsWith(' ')) substring += ' '

    // Возвращаем новую стрроку с итерационным вызовом, так как могут быть и другие вхождения
    return string.substring(0, pos1 + word1.length) +
    substring +
    word2 +
    replaceSubstring(string.substring(pos2 + word2.length), words, substring)
    }




    Regular Expression Search Option



    function replaceSubstring2(string, words, substring) {
    if (!substring.startsWith(' ')) substring = ' ' + substring
    if (!substring.endsWith(' ')) substring += ' '

    const regex = words.replace(' ', '.+?')
    return string.replaceAll(new RegExp(regex, 'g'), words.replace(' ', substring))
    }
    Lilah McPherson

  • 0
    const replaceSubstring = (string, words, substring) => {
    const [ word1, word2 ] = words.split(/\s/);
    const re = new RegExp(`(${word1}\\s?).+?(\\s?${word2})`);
    return string.replace(re, `$1${substring}$2`);
    };
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!