How do we subtract two strings in JavaScript?

IS there a way to subtract two strings?

Sample Code:-

let string1 = 'heeloo';
let string2 = 'helo';
let subtractStr = string1 - string2;

I want it to return an array/string with the leftover words - ‘eo’ in this case.

[Its fine if string2 has any extra characters since that will be invalidated. The main string here is string1] .

No, there is not a built in way to do this. You would have to write your own function.

1 Like

I see. Can you provide me with a sample or the logic on how to do it?

I honestly have never thought about it. I feel like you need a more stringent definition of what you want to have happen. What are the possible edge cases?

1 Like

When you subtract a bigger integer from a smaller one you get a negative number. I’m trying to figure out what a negative string would be :slight_smile:

1 Like

Basic Algorithm Scripting: Mutations | freeCodeCamp.org
This is what im working on right on. I know that there might be a LOT of ways to solve this, maybe even ones which end in a few lines.

What I thought of doing is to find the elements that match in each sentence and then subtract the strings and get the words which dont match.
I was close to the solution with a normal for loop and if else but I couldnt pass the cases where a character would repeat . Can post code if needed

It seems I somehow accidentally came across a solution after retrying the exercise from scratch. Thanks a lot for the answers though !

function mutation(arr) {

  let replaceWords  = arr[0].toLowerCase();

  let string2 = arr[1].toLowerCase();

  let increment = 0;

  for(let i =0; i < string2.length; i++){

    if(replaceWords.includes(string2[i])){

      increment += 1;

    }

  }

  if(increment >= string2.length){

    return true;

  }else{

    return false;

  }

}

console.log(mutation(["hello", "hey"]));

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.