user1022521
user1022521

Reputation: 537

Compare part of string in JavaScript

How do I compare a part of a string - for example if I want to compare if string A is part of string B. I would like to find out this: When string A = "abcd" and string B = "abcdef" it needs to return true. How do I do that in JavaScript? If I use substring(start, end) I do not know what values to pass to the start and end parameters. Any ideas?

Upvotes: 30

Views: 55957

Answers (7)

mix3d
mix3d

Reputation: 4333

Javascript ES6/ES2015 has String.includes(), which has nearly all browser compatibility except for IE. (But what else is new?)

let string = "abcdef";
string.includes("abcd"); //true
string.includes("aBc"); //false - .includes() is case sensitive

Upvotes: 19

mwag
mwag

Reputation: 4035

Using indexOf or match is unnecessarily slow if you are dealing with large strings and you only need to validate the beginning of the string. A better solution is to use startsWith() or its equivalent function-- from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith:

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(searchString, position){
      position = position || 0;
      return this.substr(position, searchString.length) === searchString;
  };
}

Upvotes: 5

palaѕн
palaѕн

Reputation: 73896

Like this:

var str = "abcdef";
if (str.indexOf("abcd") >= 0)

Note that this is case-sensitive. If you want a case-insensitive search, you can write

if (str.toLowerCase().indexOf("abcd") >= 0)

Or,

if (/abcd/i.test(str))

And a general version for a case-insensitive search, you can set strings of any case

if (stringA.toLowerCase().indexOf(stringB.toLowerCase()) >= 0)

Upvotes: 19

Chung-Min Cheng
Chung-Min Cheng

Reputation: 29

Using regular expression might help you.

var patt = new RegExp(stringA, 'i');
if(stringB.match(patt)){                            
   return true;
}

Upvotes: 2

senK
senK

Reputation: 2802

You can try the javascript search also

if( stringA.search(stringB) > -1){
}

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

You can use indexOf:

if ( stringB.indexOf( stringA ) > -1 ) {
  // String B contains String A
} 

Upvotes: 27

lyomi
lyomi

Reputation: 4370

"abcdef".indexOf("abcd") !== -1 should be okay

Upvotes: 3

Related Questions