猿问

使用 for 循环替换子字符串

我正在尝试用“拒绝”一词替换子字符串。例如:如果原始字符串是“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。我为代码风格道歉。


哈士奇WWW
浏览 151回答 3
3回答

斯蒂芬大帝

如果您知道要替换的子字符串的长度,那么您可以迭代该字符串并检查该长度的所有可能子字符串,就像您通过“窗口”查看一样:function replace(full, partial, placeholder) {&nbsp; for (let i = 0; i <= full.length - partial.length; i++) {&nbsp; &nbsp; const current = full.substring(i, i + partial.length);&nbsp; &nbsp; if (current === partial) {&nbsp; &nbsp; &nbsp; const prefix = full.substring(0, i);&nbsp; &nbsp; &nbsp; const suffix = full.substring(i + partial.length);&nbsp; &nbsp; &nbsp; return `${prefix}${placeholder}${suffix}`;&nbsp; &nbsp; }&nbsp; }}const ans = replace('abcdefghij', 'def', 'DENIED');console.log(ans);如果你想替换所有出现的地方,只是不要在第一次匹配后返回值:function replaceAll(full, partial, placeholder) {&nbsp; let tmp = full;&nbsp; for (let i = 0; i <= tmp.length - partial.length; i++) {&nbsp; &nbsp; const current = tmp.substring(i, i + partial.length);&nbsp; &nbsp; if (current === partial) {&nbsp; &nbsp; &nbsp; const prefix = tmp.substring(0, i);&nbsp; &nbsp; &nbsp; const suffix = tmp.substring(i + partial.length);&nbsp; &nbsp; &nbsp; tmp = `${prefix}${placeholder}${suffix}`;&nbsp; &nbsp; &nbsp; i += placeholder.length;&nbsp; &nbsp; }&nbsp; }&nbsp; return tmp;}const ans = replaceAll('abcdefghijdef', 'def', 'DENIED');console.log(ans);

叮当猫咪

由于您没有指定是要进行完全替换还是单数替换,因此我修改了它以允许使用一个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 singularfunction replace(word, sub, replacement, replaceall){&nbsp; &nbsp;replaceall = replaceall || false; //default to singular replace&nbsp; &nbsp;//Get the first index of the sub to replace&nbsp; &nbsp;const startOfReplace = word.indexOf(sub);&nbsp; &nbsp;//get the ending index of where the substring to be replaced ends&nbsp; &nbsp;const endOfReplace = startOfReplace + sub.length - 1;&nbsp; &nbsp;&nbsp; &nbsp;//variable to hold new word after replace&nbsp; &nbsp;let replacedWord = "";&nbsp; &nbsp;//If the substring is found do the replacement with the given replacement word&nbsp; &nbsp;if(startOfReplace > -1){&nbsp; &nbsp; &nbsp; for(let i = 0; i < word.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(i == startOfReplace){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;replacedWord += replacement;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}else if(i >= startOfReplace && i <= endOfReplace){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; replacedWord += word[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}else{ //set the return to the passed in word as no replacement can be done&nbsp; &nbsp; &nbsp; replacedWord = word;&nbsp; &nbsp; &nbsp; return replacedWord;&nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;if(replaceall) //if boolean is true, recursively call function to replace all occurrences&nbsp; &nbsp; &nbsp; //recursive call if the word has the sub more than once&nbsp; &nbsp; &nbsp; return replace(replacedWord, sub, replacement);&nbsp; else&nbsp; &nbsp; &nbsp;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));

慕勒3428872

const source = "abcdefg";const target = "bcd";const replacer = "DENIED";const replace = (source, target, replacer) => {&nbsp; const position = source.indexOf(target);&nbsp; if(position === -1) return source;&nbsp; let output = source.substr(0, position)&nbsp; output += replacer&nbsp; output += source.substr(position + target.length);&nbsp; return output}const replaceAll = (source, target, replacer) => {&nbsp; &nbsp; &nbsp;let output = source;&nbsp; &nbsp; &nbsp;do{&nbsp; &nbsp; &nbsp; &nbsp;output = replace(output, target, replacer)&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;while(output !== replace(output, target, replacer))&nbsp; &nbsp; &nbsp;return output;}console.log(replace(source, target, replacer))并且可以肯定的是,最好的解决方案,最容易理解,干净和优雅的是:const replaceAll = (source, target, replacer) => {&nbsp; return source.split(target).join(replacer)}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答