freeCodeCamp/guide/russian/certifications/javascript-algorithms-and-d.../intermediate-algorithm-scri.../search-and-replace/index.md

13 KiB
Raw Blame History

title localeTitle
Search and Replace Поиск и замена

:triangular_flag_on_post: Не забудьте использовать Read-Search-Ask если вы застряли. Попробуйте подключить программу :busts_in_silhouette: и напишите свой собственный код :pencil:

:checkered_flag: Проблема Объяснение:

Вы создадите программу, которая принимает предложение, затем ищет слово в нем и заменяет его на новый, сохраняя в верхнем регистре, если он есть.

Связанные ссылки

:speech_balloon: Подсказка: 1

  • Найдите индекс, где before находится в строке.

попытаться решить проблему сейчас

:speech_balloon: Подсказка: 2

  • Проверьте корпус первой буквы.

попытаться решить проблему сейчас

:speech_balloon: Подсказка: 3

  • Строки неизменяемы, вам нужно будет сохранить изменения в другой переменной, даже если вы должны повторно использовать одно и то же, чтобы они выглядели как изменения, которые были сделаны с использованием только одной переменной.

попытаться решить проблему сейчас

Осторожно, спойлеры!

предупреждающий знак

Решение впереди!

:beginner: Решение базового кода:

function myReplace(str, before, after) { 
  // Find index where before is on string 
  var index = str.indexOf(before); 
  // Check to see if the first letter is uppercase or not 
  if (str[index] === str[index].toUpperCase()) { 
    // Change the after word to be capitalized before we use it. 
    after = after.charAt(0).toUpperCase() + after.slice(1); 
  } 
  // Now replace the original str with the edited one. 
  str = str.replace(before, after); 
 
  return str; 
 } 
 
 // test here 
 myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"); 

:rocket: Код запуска

Код Объяснение:

  • Используйте indexOf() , чтобы найти местоположение ранее в строке.
  • Если первая буква предшествует заглавной, измените первую букву после в верхний регистр.
  • Заменить ранее в строке с после.
  • Верните новую строку.

Связанные ссылки

:sunflower: Решение промежуточного кода:

function myReplace(str, before, after) { 
 //Create a regular expression object 
  var re = new RegExp(before,"gi"); 
 //Check whether the first letter is uppercase or not 
  if(/[AZ]/.test(before[0])){ 
  //Change the word to be capitalized 
    after = after.charAt(0).toUpperCase()+after.slice(1); 
     } 
     //Replace the original word with new one 
  var  newStr =  str.replace(re,after); 
 
 return newStr; 
 } 
 
 // test here 
 myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"); 

:rocket: Код запуска

Код Объяснение:

  • В этом решении регулярное выражение [AZ] используется для проверки, является ли символ прописным.
  • Создайте новый объект регулярного выражения, re .
  • Если заглавная буква первой буквы предшествует , измените первую букву после в верхний регистр.
  • Замените его до после строки.
  • Верните новую строку.

Связанные ссылки

  • Ресурсы JS Regex

:rotating_light: Расширенное решение для кода:

function myReplace(str, before, after) { 
 
    // create a function that will change the casing of any number of letter in parameter "target" 
    // matching parameter "source" 
    function applyCasing(source, target) { 
        // split the source and target strings to array of letters 
        var targetArr = target.split(""); 
        var sourceArr = source.split(""); 
        // iterate through all the items of sourceArr and targetArr arrays till loop hits the end of shortest array 
        for (var i = 0; i < Math.min(targetArr.length, sourceArr.length); i++){ 
            // find out the casing of every letter from sourceArr using regular expression 
            // if sourceArr[i] is upper case then convert targetArr[i] to upper case 
            if (/[AZ]/.test(sourceArr[i])) { 
                targetArr[i] = targetArr[i].toUpperCase(); 
            } 
            // if sourceArr[i] is not upper case then convert targetArr[i] to lower case 
            else targetArr[i] = targetArr[i].toLowerCase(); 
        } 
        // join modified targetArr to string and return 
        return (targetArr.join("")); 
    } 
 
    // replace "before" with "after" with "before"-casing 
    return str.replace(before, applyCasing(before, after)); 
 } 
 
 // test here 
 myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"); 

:rocket: Код запуска

Код Объяснение:

  • Оба аргумента before и after передаются как аргументы applyCasing() .
  • Функция applyCasing() используется для изменения случая соответствующих символов в targetArr, т. Е. После того , как в соответствии с символами в sourceArr, то есть раньше .
  • replace() используется для замены before с после , корпус которого такой же, как и раньше .

:rotating_light: Расширенное решение для кода:

// Add new method to the String object, not overriding it if one exists already 
 String.prototype.capitalize =  String.prototype.capitalize || 
    function() { 
        return this[0].toUpperCase() + this.slice(1); 
    }; 
 
 const Util = (function () { 
 // Create utility module to hold helper functions 
    function textCase(str, tCase) { 
        // Depending if the tCase argument is passed we either set the case of the 
        // given string or we get it. 
        // Those functions can be expanded for other text cases. 
 
        if(tCase) { 
            return setCase(str, tCase); 
        } else { 
            return getCase(str); 
        } 
 
        function setCase(str, tCase) { 
            switch(tCase) { 
                case "uppercase": return str.toUpperCase(); 
                case "lowercase": return str.toLowerCase(); 
                case "capitalized": return str.capitalize(); 
                default: return str; 
            } 
        } 
 
        function getCase(str) { 
            if (str === str.toUpperCase()) { return "uppercase"; } 
            if (str === str.toLowerCase()) { return "lowercase"; } 
            if (str === str.capitalize()) { return "capitalized"; } 
            return "normal"; 
        } 
    } 
 
    return { 
        textCase 
    }; 
 })(); 
 
 function myReplace(str, before, after) { 
    const { textCase } = Util; 
    const regex = new RegExp(before, 'gi'); 
    const replacingStr = textCase(after, textCase(before)); 
 
    return str.replace(regex, replacingStr); 
 } 

:rocket: Код запуска

:rotating_light: Advanced Code Solution Альтернатива 2:

function myReplace(str, before, after) { 
  const myArr = str.split(' '); 
  const [wordToReplace] = myArr.filter(item => item === before); 
  return  wordToReplace[0].toUpperCase() !== wordToReplace[0] 
  ? myArr.map(item => item === before ? after : item).join(' ') 
  : myArr.map(item => item === before? after[0].toUpperCase() + after.slice(1) : item).join(' '); 
 } 
 
 // test: 
 myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"); 

Связанные ссылки

:clipboard: ПРИМЕЧАНИЯ ДЛЯ ВЗНОСОВ:

  • :warning: НЕ добавляйте решения, похожие на любые существующие решения. Если вы считаете, что это похоже, но лучше , попробуйте объединить (или заменить) существующее подобное решение.
  • Добавьте объяснение своего решения.
  • Классифицируйте решение в одной из следующих категорий - Basic , Intermediate и Advanced . :traffic_light:
  • Пожалуйста, добавьте свое имя пользователя, только если вы добавили соответствующее основное содержимое . ( :warning: НЕ удаляйте существующие имена пользователей )

Видеть :point_right: Wiki Challenge Solution Template для Wiki Challenge Solution Template для справки.