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?
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 (===)”.
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.
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.
You can use indexOf
:
if ( stringB.indexOf( stringA ) > -1 ) { // String B contains String A }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With