Reputation: 655
how can I check with javascript if one string contains an other string? I have like something like:
var a = "Paris, France"
var b = "Paris.."
a.match(b) //returns "Paris, " but should return null
I think the problem is that match uses regexp. Is there a possibility to allow Sympols like
.,-/\
etc. ?
Thanks
Upvotes: 0
Views: 3836
Reputation: 3635
You can use indexOf
method:
var a = "Paris, France"
var b = "Paris.."
if(a.indexOf(b) != -1){
//string a contains string b
}
Upvotes: 0
Reputation: 3778
To see if one string contains another, use String.indexOf()
:
var str = 'Paris, France';
var strIndex = str.indexOf('Paris..');
if(strIndex == -1) {
//string not found
} else {
//string found
}
But, just in case you want to have a contains()
function, you can add it to String
as below:
if(!('contains' in String.prototype)) {
String.prototype.contains = function(str, startIndex) {
return -1 !== String.prototype.indexOf.call(this, str, startIndex);
};
}
var str = 'Paris, France';
var valid = str.contains('Paris..');
if(valid) {
//string found
} else {
//string not found
}
Upvotes: 2