I have a string "SünilGarg"
now I want to check if above string contains chars from second string "üG#$".
The one way is to check every single char of second string with first string using loop. But is there any other best and efficient way to do so ?
-
So, even if only one char is from second string then true should be returned? or all characters should be from second string?gurvinder372– gurvinder3722016年03月14日 12:54:30 +00:00Commented Mar 14, 2016 at 12:54
-
if there is any match then returnCode Guru– Code Guru2016年03月14日 12:55:45 +00:00Commented Mar 14, 2016 at 12:55
6 Answers 6
Try this one:
var mainString = "SünilGarg",
charsString = "üG#$";
var contains = Array.prototype.some.call(mainString, function(char) {
return charsString.indexOf(char) !== -1;
});
Because strings are array like objects (partially), it's easy to use some array methods on them.
2 Comments
partially array like objects. :)I'm pretty sure the fastest way is to loop over the larger string and for each character check if the shorter string contains it:
function containsAny(haystack, needles){
for(var i = 0; i < haystack.length; i++){
for(var j = 0; j < needles.length; j++){
if(haystack[i] === needles[j]) {
return true;
}
}
}
return false;
}
Here's some evidence: http://jsperf.com/stringcontainsany
EDIT:
Actually, string.indexOf is faster than indexing into the string, so this is more efficient:
function containsAny(haystack, needles) {
for (var i = 0; i < haystack.length; i++) {
if (needles.indexOf(haystack[i]) !== -1) {
return true;
}
}
return false;
}
1 Comment
The below code should work
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
var fString = 'SünilGarg';
var sString = RegExp.escape('üG#$');
var pattern = new RegExp('['+ sString +']');
pattern.test(fString); //Will return true
2 Comments
Use indexOf to check if there is a character match
function checkString(myString,withCompare){
var dumArray = withCompare.split('')
var i = 0;
for(i;i<dumArray.length;i++){
if(myString.indexOf(dumArray[i]) ==-1){
// do nothing
console.log('nothing')
}
else{
console.log(dumArray[i])
}
}
}
checkString('hello','mvo');
Comments
Using an es6 one liner:
var str = 'SünilGarg';
var match = 'üG#$';
var res = match.split('').some(v => str.includes(v));
console.log(res);
Note that this will work in modern browsers like newest chrome or firefox only
Or for wider support, using es5:
var res = match.split('').some(function (v) {
return str.indexOf(v) > -1;
});
Comments
I'm not the brightest in this case but I'd go with one loop and indexOff. eg:
function isMatch(str) {
var matchStr = 'üG#$';
for (var i = 0; i < matchStr.length; i++) {
if (str.indexOf(matchStr[i]) !== -1) {
return true;
}
}
return false;
}
Not sure if there are any smarter moves, but I think regex might be slower.