const str = 'hello world!';
const result = /^hello/.test(str);
console.log(result); // true
/**
The test() method executes a search for a match between
a regular expression and a specified string
*/
JavaScript | RegExp test() Method
The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false.
Syntax:
RegExpObject.test(str)
Where str is the string to be searched. This is required field.
// The string:
var str = "Hello world!";
// Look for "Hello"
var patt = /Hello/g;
var result = patt.test(str);
// Look for "W3Schools"
patt2 = /W3Schools/g;
result2 = patt2.test(str);