Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare part of string in JavaScript

Tags:

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?

like image 401
user1022521 Avatar asked Dec 12 '12 06:12

user1022521


People also ask

Can I compare strings in JavaScript?

In JavaScript, strings can be compared based on their “value”, “characters case”, “length”, or “alphabetically” order: To compare strings based on their values and characters case, use the “Strict Equality Operator (===)”.

How do you equate two strings in JavaScript?

To compare two strings in JavaScript, use the localeCompare() method. The method returns 0 if both the strings are equal, -1 if string 1 is sorted before string 2 and 1 if string 2 is sorted before string 1.

How do you check if one string is greater than another in JavaScript?

To see whether a string is greater than another, JavaScript uses the so-called “dictionary” or “lexicographical” order. In other words, strings are compared letter-by-letter. The algorithm to compare two strings is simple: Compare the first character of both strings.


1 Answers

You can use indexOf:

if ( stringB.indexOf( stringA ) > -1 ) {   // String B contains String A }  
like image 128
elclanrs Avatar answered Oct 04 '22 03:10

elclanrs