4

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 "aDENIEDefg".

I can't use .replace or anything else, just .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. I apologize for the code style.

3
  • can you use indexOf ? Commented Oct 19, 2020 at 18:55
  • yes! i can use indexOf. I thought about how to use indexOf, but I didn't come up with a solution Commented Oct 19, 2020 at 18:58
  • @thatdudemasquerade Do you want to replace multiple occurrences? So for instance your example string was abcdefgbcd, should you get aDENIEDefgDENIED or aDENIEDefgbcd??? Commented Oct 19, 2020 at 19:29

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

@RyanWilson I didn't realize the OP wanted to replace all occurrences, but added this case as well. Thanks!
I'm just guessing that the OP needs to replace all occurrences, but I would wager you'd want to be able to do a full replace.
1

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.

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

2 Comments

Big thanks to you! Your code is very helpful, I understand what my mistake was.
@thatdudemasquerade You're welcome. Glad to help! :)
1
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)
}

2 Comments

This fails if the source is abcdefgbcd, it only replaces the first occurence.
You don't say replaceAll. normale String.replace works for first occurrence

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.