9 minutes read

JavaScript provides a set of predefined methods that make it easy for developers to perform string-related operations.

In this topic, you'll learn how to compare two strings using localeCompare() and retrieve string matches with match(). You'll also discover how to search for the index position of a string within a string using the search() method.

The localeCompare method

The localeCompare() method compares strings lexicographically (i.e., alphabetically). The two strings are compared in the current locale based on their sort order. The locale is determined by the language settings of the browser.

You can see the syntax of the localeCompare() method below:

referenceStr.localeCompare(string)

Here, the string is compared lexicographically with the referenceStr, and an integer is returned. The value of the integer is determined by whether the referenceStr comes before, after, or is equal to the string. And the possible return values of the localeCompare() method are as follows:

  • Negative (-1) when the referenceStr comes before the string in the sort order.

  • Positive (1) when the referenceStr comes after the string in the sort order.

  • 0 if the referenceStr and the string are equivalent.

The return values might not be -1 or 1 — this depends on the particular browser. For example, some browsers may return -2 instead of -1, and 2 instead of 1. So it's important that you check for positive or negative return values rather than a specific number.

The below examples demonstrate how the localeCompare() method works:

// Alphabetically, 'b' comes before 'f'
let compare1 = 'b'.localeCompare('f');
console.log(compare1); // -1

// Alphabetically, 'javascript' comes after 'java'
let compare2 = 'javascript'.localeCompare('java');
console.log(compare2); // 1

// Alphabetically, 'c' is the same as 'c'
let compare3 = 'c'.localeCompare('c');
console.log(compare3); // 0

The match method

You can use the match() method to find matches in a string against a regular expression. Its syntax is as follows:

string.match(regExp)

match() returns an array containing all the matches it finds if the g flag is used in the regular expression. However, if the regex doesn't include the g flag, match() will behave like regexp.exec(string), returning only the first match.

let txt = "Hello JavaScript! It's fun to learn string methods in javascript";

// Regular expression with 'g' modifier
let regExp = /JavaScript/g;

// string.match() function
let matchFound = txt.match(regExp);

// Printing the array object
console.log(matchFound);

Output:

Collapsed browser console output with an array of one string element – JavaScript

In the above example, as the g flag is present in the variable regExp, the return value is an array that contains all the instances of the word JavaScript. Note that matching is case-sensitive, so only one instance is found on this occasion.

Now let's look at an example in which the i flag is used instead:

let txt = "Hello JavaScript! It's fun to learn string methods in javascript";

// Regexp with 'i' modifier
let regExp = /javascript/i;

let matchFound = txt.match(regExp);

// Printing the array object
console.log(matchFound);

Output:

Expanded browser console output with the array of one string element – JavaScript that cointanis result of match method

This time, the presence of the i flag in the regExp means that case-insensitive matching is performed. So the match found is the first instance of the word JavaScript regardless of letter case. Only one match is returned because the g flag is not used.

In the below example, the flags are combined:

let txt = "Hello JavaScript! It's fun to learn string methods in javascript";

// Regexp with 'g' and 'i' modifiers
let regExp = /javascript/gi;

let matchFound = txt.match(regExp);

// Printing the array object
console.log(matchFound);

Output:

Collapsed browser console output with an array of two JavaScript elements

As you can see, using the g and i flags together results in all matches for the regex pattern being returned, whether letters have been capitalized or not. The words JavaScript and javascript are therefore both found.

When it comes to string comparison with regex, the test() method is more efficient than the match() method. It returns a boolean value indicating whether a match has been identified. So, if that's all you need, you can use test() instead.

The search method

The search() method checks if a string contains a match for the given regular expression and then returns the position of the match.

The syntax of the search() method is shown below:

string.search(regExp)

The argument passed to search() must be a regex. If it isn't, the search() method implicitly converts it into a regex internally.

If a match is found in the string, search() will return the index where the pattern is first identified. Or, if no match is found, -1 will be returned.

const str = "No need to light a night-light on a light night like tonight";

// Regex is passed as an argument 
let lightRegExp = /light/;
str.search(lightRegExp); // 11

// String will be converted to regexp internally
let night = "night";
str.search(night); // 19

// Passed argument is not present in str
let day = "day";
str.search(day); // -1

Conclusion

You now know how to compare two strings lexicographically using localeCompare(). And you have learned how to retrieve the results of matching a string against a regex pattern with the match() method. You've also discovered that the search() method can be used to find the index position of a string within a string.

80 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo