In this article, you’ll learn how to check whether a string starts with a regex in javascript. We use the test()
function to check whether a string starts with a regex or not.
Make sure your regular expression starts with caret (^
), which is a special character that represents the start of the string.
The test()
function will search the string and return true
if the string contains a match otherwise, it returns false
.
let valid = /^D/.test("Does string start with 'D'.");
console.log(valid);
//When String Starts with D, it returns true
// Output ==> true
valid = /^D/.test("What a beautiful day.");
console.log(valid);
//When String Starts Does not with D, it returns false
// Output ==> false
You can also use the new RegExp()
constructor to turn a string into a regular expression.
const string = '^Does';
const regex = new RegExp(string);
console.log(regex.test("Does string start with 'Does'."));
// Output ==> true
console.log(regex.test("What a beautiful day."));
// Output ==> false
In your case you're looking for case insensitive, you can add modifiers ‘i
’ (case insensitive) as a second parameter with the new regex()
constructor. The 'i
' flag makes a regular expression case insensitive.
console.log(/^A/i.test('ABC'));
// Output ==> true
console.log(/^A/i.test('abc'));
// Output ==> true
console.log(/^A/i.test('bac'));
// Output ==> false
// Or using RegExp constructor
const regexp = new RegExp('^A', 'i');
console.log(regexp.test('ABC'));
// Output ==> true
console.log(regexp.test('abc'));
// Output ==> true
console.log(regexp.test('bac'));
// Output ==> false
I hope this article will help you to understand how to check whether a string starts with a regex in javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments