Regex / String Methods
Regular Expressions: Regex / String Methods
Which string method would you use to find matches in JavaScript using regex?
View Answer:
let string = "Hello, world!";
let regex = /world/;
let result = string.match(regex);
console.log(result); // Logs: ["world"]
In this example, match()
is used to find the word "world" in the string. The method returns an array with the matched results, or null
if no matches were found.
In addition to match()
, the RegExp
object's exec()
method can also be used to find matches in a string, offering more flexibility and control such as global and sticky searching.
Here's an example using exec()
:
let string = "Hello, world!";
let regex = /world/g; // 'g' for global search
let result;
while ((result = regex.exec(string)) !== null) {
console.log(`Found ${result[0]} at index ${result.index}`);
}
This will log all the matches along with their indices.
Can you explain the function of the match() string method?
View Answer:
// Mode #1:
let str = 'I love JavaScript';
let result = str.match(/Java(Script)/);
console.log(result[0]); // JavaScript (full match)
console.log(result[1]); // Script (first capturing group)
console.log(result.length); // 2
// Additional information:
console.log(result.index); // 7 (match position)
console.log(result.input); // I love JavaScript (source string)
// Mode #2:
let str = 'I love JavaScript';
let result = str.match(/Java(Script)/g);
console.log(result[0]); // JavaScript
console.log(result.length); // 1
// Mode #3:
let str = 'I love JavaScript';
let result = str.match(/HTML/);
console.log(result); // null
console.log(result.length); // Error: Cannot read property 'length' of null
// * If we want the result to be an array, we can write like this:
let result = str.match(regexp) || [];
Can you explain the function of the matchAll() string method?
View Answer:
let str = '<h1>Hello, world!</h1>';
let regexp = /<(.*?)>/g;
let matchAll = str.matchAll(regexp);
console.log(matchAll); // [object RegExp String Iterator], not array, but an iterable
matchAll = Array.from(matchAll); // array now
let firstMatch = matchAll[0];
console.log(firstMatch[0]); // <h1>
console.log(firstMatch[1]); // h1
console.log(firstMatch.index); // 0
console.log(firstMatch.input); // <h1>Hello, world!</h1>
What is the difference between match() and matchAll() String methods?
View Answer:
Here are examples of using match()
and matchAll()
in JavaScript:
let str = "apple, banana, apple";
// Using match()
let matchResult = str.match(/apple/g);
console.log(matchResult); // ['apple', 'apple']
// Using matchAll()
let matchAllResult = [...str.matchAll(/(apple)/g)];
console.log(matchAllResult); // [{0: 'apple', 1: 'apple', groups: undefined}, {0: 'apple', 1: 'apple', groups: undefined}]
The matchAll()
function returns more information about each match, including index and input string.
Is it possible to use the str.split() method with a regular expression?
View Answer:
// Example: str.split(substring)
console.log('12-34-56'.split('-')); // array of ['12', '34', '56']
// Example: str.split(regexp)
console.log('12, 34, 56'.split(/,\s*/)); // array of ['12', '34', '56']
Can you explain the function of the search() string method?
View Answer:
let str = 'A drop of ink may make a million think';
console.log(str.search(/ink/i)); // 10 (first match position)
Can you explain the function of the str.replace() string method?
View Answer:
// replace all dashes by a colon
console.log('12-34-56'.replace(/-/g, ':')); // 12:34:56
let str = 'John Smith';
// swap first and last name
console.log(str.replace(/(john) (smith)/i, '$2, $1')); // Smith, John
// Using a function as the second argument
let str = 'html and css';
let result = str.replace(/html|css/gi, (str) => str.toUpperCase());
console.log(result); // HTML and CSS
// Replace each match by its position in the string:
console.log('Ho-Ho-ho'.replace(/ho/gi, (match, offset) => offset)); // 0-3-6
What's the difference between the replace() and replaceAll() methods?
View Answer:
// replace all dashes by a colon
console.log('12-34-56'.replaceAll('-', ':')); // 12:34:56
Can you explain the function of the regexp.exec() object method?
View Answer:
let str = 'More about JavaScript at https://javascript.info';
let regexp = /javascript/gi;
let result;
while ((result = regexp.exec(str))) {
console.log(`Found ${result[0]} at position ${result.index}`);
// Found JavaScript at position 11, then
// Found javascript at position 33
}
// Search from a given position by manually setting lastIndex.
let str = 'Hello, world!';
let regexp = /\w+/g; // without flag "g", lastIndex property is ignored
regexp.lastIndex = 5; // search from 5th position (from the comma)
console.log(regexp.exec(str)); // world
// replace flag g with y
let str = 'Hello, world!';
let regexp = /\w+/y;
regexp.lastIndex = 5; // search exactly at position 5
console.log(regexp.exec(str)); // null
Can you explain the function of the regexp.test() method?
View Answer:
// Basic Example:
let str = 'I love JavaScript';
// these two tests do the same
console.log(/love/i.test(str)); // true
console.log(str.search(/love/i) != -1); // true
// An example with the negative answer:
let str = 'Bla-bla-bla';
console.log(/love/i.test(str)); // false
console.log(str.search(/love/i) != -1); // false
// Use it to search from a given position with flag g:
let regexp = /love/gi;
let str = 'I love JavaScript';
// start the search from position 10:
regexp.lastIndex = 10;
console.log(regexp.test(str)); // false (no match)
Are there any ramifications when we run global regexp.test repeatedly on different sources?
View Answer:
let regexp = /javascript/g; // (regexp just created: regexp.lastIndex=0)
console.log(regexp.test('javascript')); // true (regexp.lastIndex=10 now)
console.log(regexp.test('javascript')); // false
What's the difference between match() and search() in JavaScript?
View Answer:
Here are examples of using match()
and search()
in JavaScript:
let str = "I love apples, apples are my favorite fruit";
// Using match()
let matchResult = str.match(/apples/g);
console.log(matchResult); // ['apples', 'apples']
// Using search()
let searchResult = str.search(/apples/);
console.log(searchResult); // 7
In the example above, match()
returns an array with all matches, while search()
returns the position of the first match.