为了账号安全,请及时绑定邮箱和手机立即绑定

使用 for 循环替换子字符串

使用 for 循环替换子字符串

哈士奇WWW 2023-05-25 16:29:00
我正在尝试用“拒绝”一词替换子字符串。例如:如果原始字符串是“abcdefg”而要替换的子字符串是“bcd”,则预期输出是“a DENIED efg”。我不能使用.replace或其他任何东西,只是.substringfunction 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。我为代码风格道歉。
查看完整描述

3 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

如果您知道要替换的子字符串的长度,那么您可以迭代该字符串并检查该长度的所有可能子字符串,就像您通过“窗口”查看一样:


function replace(full, partial, placeholder) {

  for (let i = 0; i <= full.length - partial.length; i++) {

    const current = full.substring(i, i + partial.length);

    if (current === partial) {

      const prefix = full.substring(0, i);

      const suffix = full.substring(i + partial.length);

      return `${prefix}${placeholder}${suffix}`;

    }

  }

}


const ans = replace('abcdefghij', 'def', 'DENIED');

console.log(ans);


如果你想替换所有出现的地方,只是不要在第一次匹配后返回值:


function replaceAll(full, partial, placeholder) {

  let tmp = full;

  for (let i = 0; i <= tmp.length - partial.length; i++) {

    const current = tmp.substring(i, i + partial.length);

    if (current === partial) {

      const prefix = tmp.substring(0, i);

      const suffix = tmp.substring(i + partial.length);

      tmp = `${prefix}${placeholder}${suffix}`;

      i += placeholder.length;

    }

  }

  return tmp;

}


const ans = replaceAll('abcdefghijdef', 'def', 'DENIED');

console.log(ans);


查看完整回答
反对 回复 2023-05-25
?
叮当猫咪

TA贡献1776条经验 获得超12个赞

由于您没有指定是要进行完全替换还是单数替换,因此我修改了它以允许使用一个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));


查看完整回答
反对 回复 2023-05-25
?
慕勒3428872

TA贡献1848条经验 获得超6个赞

const source = "abcdefg";

const target = "bcd";

const replacer = "DENIED";




const replace = (source, target, replacer) => {

  const position = source.indexOf(target);

  if(position === -1) return source;

  let output = source.substr(0, position)

  output += replacer

  output += source.substr(position + target.length);

  return output

}


const replaceAll = (source, target, replacer) => {

     let output = source;

     do{

       output = replace(output, target, replacer)

     }

     while(output !== replace(output, target, replacer))

     return output;

}


console.log(replace(source, target, replacer))

并且可以肯定的是,最好的解决方案,最容易理解,干净和优雅的是:


const replaceAll = (source, target, replacer) => {

  return source.split(target).join(replacer)

}


查看完整回答
反对 回复 2023-05-25
  • 3 回答
  • 0 关注
  • 150 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号