user
How to test a regex in js ?
alphonsio

To test a regular expression (regex) in JavaScript, you can use the test() method of a regular expression object. The test() method takes a string as an argument and returns a boolean value indicating whether the string matches the regular expression or not.

Here's an example of how to use the test() method to test a regex in JavaScript:

const regex = /\d+/; // matches one or more digits
const string = '123';

const result = regex.test(string);
console.log(result); // outputs: true

In this example, the regular expression /\d+/ matches one or more digits. The test() method is called on the regular expression object and passed the string '123' as an argument. Since the string contains one or more digits, the test() method returns true.


You can also use the match() method of a string object to test a regex. The match() method returns an array of matches or null if there are no matches.

Here's an example of how to use the match() method to test a regex in JavaScript:

const regex = /\d+/g; // matches one or more digits globaly
const string = '123 abc 456';

const result = string.match(regex);
console.log(result); // outputs: [ "123", "456" ]

In this example, the match() method is called on the string '123 abc 456' and passed the regular expression /\d+/g. The method returns an array containing the matches, which are '123' and '456'.