简体   繁体   English

使用 for 循环替换子字符串

[英]Replace substring using for loop

I'm trying to replace a substring with the word 'denied'.我正在尝试用“拒绝”一词替换子字符串。 For example: if the original string is "abcdefg" and sub-string to replace is "bcd", expected output is "a DENIED efg".例如:如果原始字符串是“abcdefg”并且要替换的子字符串是“bcd”,则预期输出是“a DENIED efg”。

I can't use .replace or anything else, just .substring我不能使用.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]) {
                   
            }
        }
    }
}

I have no clue what to do next.我不知道接下来要做什么。

Here is my code to just remove characters from a string.这是我的代码,只是从字符串中删除字符。

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);
}

But this time I need not to just remove one characters, but find a sub-string to replace with DENIED .但这一次我不需要只删除一个字符,而是找到一个子字符串来替换为DENIED I apologize for the code style.我为代码风格道歉。

If you know the length of the substring you're trying to replace, then you can just iterate the string and examine all possible substrings of this length, as you were looking through a "window":如果您知道要替换的子字符串的长度,那么您可以只迭代字符串并检查该长度的所有可能子字符串,就像您通过“窗口”查看一样:

 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);

If you want to replace all occurrences, just don't return the value after the first match:如果要替换所有匹配项,请不要在第一次匹配后返回值:

 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);

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))

and for sure best solution, easiest to understand, clean and elegant is :当然最好的解决方案,最容易理解,干净和优雅是:

const replaceAll = (source, target, replacer) => {
  return source.split(target).join(replacer)
}

Since you didn't specify whether you want to do a full replace or a singular, I've modified this to allow for a boolean parameter, this boolean says whether to do a singular or full replace.由于您没有指定是要进行完全替换还是单数替换,因此我对其进行了修改以允许使用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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM