Reputation: 39384
I have the following strings:
var a = "vm.model.password";
var b = "vm.model.passwordCheck";
And I have the following:
var sa = "Password";
var sb = "PasswordCheck";
I need to check that sa is contained in a and sb in b.
So to compare I need to check the string in a or b after the dot. And check if the sa is equal to that string but making the first letter of sa to lowercase first.
I was doing something like:
a.indexOf(sa.toLowerCase()) > -1;
But the problem is that sa would be a match of b to and sb would not be a match for b because it starts with P and not p.
What is the best way to do this?
Upvotes: 1
Views: 967
Reputation: 6473
Something like...
var a = "vm.model.password";
var b = "vm.model.passwordCheck";
var sa = "Password";
var sb = "PasswordCheck";
var endA = a.substring(a.lastIndexOf('.') + 1).toLowerCase();
var endB = b.substring(a.lastIndexOf('.') + 1).toLowerCase();
if (endA.includes(sa.toLowerCase())) {
alert("A match");
}
if (endB.includes(sb.toLowerCase())) {
alert("B match");
}
Obviously, you should check that it contains a '.' or that the lastIndexOf result is >= 0, etc, but I've avoided such validations for simplicity here.
Upvotes: 1
Reputation: 13886
As far as getting the last word:
what about using str.lastIndexOf('.')
which is much faster than split():
var a = "vm.model.password";
var b = "vm.model.passwordCheck";
console.log(a.slice(a.lastIndexOf('.') + 1))
// a .toLowerCase at the end should do it
JSbin: https://jsbin.com/komowi/edit?js,console
Given how you are running into problems with uppercase/lowercase letters it might be time to look at a RegExp which has an 'i' flag on it which means it will match with caseMDN RegExp This isnt needed per say, but surely will help down the road
Upvotes: 4
Reputation: 1132
How about this:
a.toLowerCase().split('.').pop() === sa.toLowerCase()
b.toLowerCase().split('.').pop() === sb.toLowerCase()
Upvotes: 1
Reputation: 145
With pop() you get the last element of the array.
if( sa.toLowerCase() == a.split(".").pop() ){
//your code here
}
Upvotes: 1
Reputation: 17616
You could do something like this, if the word you want to check is always at the end.
var aArray = a.split(".");
sa.toLowerCase() === aArray[aArray.length-1].toLowerCase();
Upvotes: 1