Skip to content
Advertisement

Check if match is from right or left side of the stringB and return the difference

We have this code:

const stringA = "enjoying your new car";
const stringB = "are you enjoying your new car";

var regexp = new RegExp(stringA + "$", "ig");
const notIncluded = stringB.replace(regexp, '');

console.log(notIncluded);

Here is the rule:

stringA always is a part of stringB and it matches some portion of stringB from right or left.

For instance in the above code we have stringA which is matching a part of stringB from the right of stringB . right?

The second rule is we want to fill notIncluded with a portion of stringB which is not included in stringA… As our code suggests… ok?

Now I need a function to give us the same notIncluded just as the above code (stringB – stringA) somehow!!!

But I want another functionality here:

I want an if else statement to check if the matching is from right side of the stringB (like what we have in the above) or from left side.

So if we have these:

const stringA = "enjoying your new car";
const stringB = "are you enjoying your new car";

the notIncluded would be :

"are you"

and the check (if statement or the variable) shows the match is from right.

In opposite if we have these:

const stringA = "enjoying your new car";
const stringB = "enjoying your new car are you";

the notIncluded would be the same again:

"are you"

This time the check (if statement or the variable) shows the match is from left side of the stringB.

Advertisement

Answer

You could just use string.startsWith and string.endsWith.

const stringA = "enjoying your new car";
const stringB = "are you enjoying your new car";
let fromLeft = false, fromRight = false;
let notIncluded = "";

if (stringB.startsWith(stringA)) {
  fromLeft = true;
  notIncluded  = stringB.substr(stringA.length);
} else if (stringB.endsWith(stringA)) {
  fromRight = true;
  notIncluded = stringB.substr(0, stringB.length - stringA.length)
}

console.log(fromLeft, fromRight, notIncluded);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement