使用for循环替换子字符串

假面舞会

我正在尝试用“ denied”一词替换一个子字符串。例如:如果原始字符串为“ abcdefg”,而要替换的子字符串为“ bcd”,则预期输出为“ a DENIED efg”。

.replace什么也不能用.substring

function replacer (variable, replace) {
    for (let a = variable.length - 1; a >=0; a--) {
        for (let b = replace.length - 1; b >= 0; b--) {
            if (replace[b] === variable[a]) {
                   
            }
        }
    }
}

我不知道下一步该怎么做。

这是我的代码,仅用于删除字符串中的字符。

let stringToReturn = original;
  for (let a = toDelete.length - 1; a >= 0; a--) {
    for (let b = original.length - 1; b >= 0; b--) {
      if (original[b] === toDelete[a]) {
           stringToReturn = stringToReturn.substring(0, b) + stringToReturn.substring(b + 1, stringToReturn.length);   
          } else {
           continue;
      }
    }
  }
alert(stringToReturn);
}

但是这一次,我不必仅删除一个字符,而是要找到一个子字符串替换为DENIED我为代码风格表示歉意。

瑞安·威尔逊(Ryan Wilson)

由于您未指定要执行完全替换还是单数替换,因此我已对此进行了修改以允许使用boolean参数,这boolean表示是执行单数替换还是完全替换。

const replaceword = "DENIED";
const testword = "abcdef";
const testword2 = "abcdefdexyz";
const testword3 = "hello I don't have the sub";
//function takes a word parameter - the word to do a replace on
//and sub parameter of what to replace
//and replacement parameter of what to replace the substring with
//replaceall is a boolean as to whether to do a full replace or singular
function replace(word, sub, replacement, replaceall){
   replaceall = replaceall || false; //default to singular replace
   //Get the first index of the sub to replace
   const startOfReplace = word.indexOf(sub);
   //get the ending index of where the substring to be replaced ends
   const endOfReplace = startOfReplace + sub.length - 1;
   
   //variable to hold new word after replace
   let replacedWord = "";
   //If the substring is found do the replacement with the given replacement word
   if(startOfReplace > -1){
      for(let i = 0; i < word.length; i++){
         if(i == startOfReplace){
             replacedWord += replacement;
         }else if(i >= startOfReplace && i <= endOfReplace){
             continue;
         }else{
            replacedWord += word[i];
         }
      }
   }else{ //set the return to the passed in word as no replacement can be done
      replacedWord = word;
      return replacedWord;
   }
               
   if(replaceall) //if boolean is true, recursively call function to replace all occurrences
      //recursive call if the word has the sub more than once
      return replace(replacedWord, sub, replacement);
  else
     return replacedWord; //else do the singular replacement
}

console.log(replace(testword, "de", replaceword));
console.log(replace(testword2, "de", replaceword, true));
console.log(replace(testword3, "de", replaceword));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章