How to useRegular Expression (RegExp) in Javascript

Regular expressions provide a flexible way to match patterns within strings. We can use a regular expression pattern to check if a string starts with another string.

JavaScript
function startsWith(str, substr) {
    // Escape special characters in the substring
    const escapedSubstr = substr.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    // Create a regular expression pattern to match the start of the string
    const pattern = new RegExp('^' + escapedSubstr);
    // Test if the string matches the pattern
    return pattern.test(str);
}

console.log(startsWith('Hello World', 'Hello')); // Output: true
console.log(startsWith('JavaScript', 'Script')); // Output: false

Output
true
false



How to check if a string “StartsWith” another string in JavaScript ?

In JavaScript, the startsWith()’ method is a built-in method that allows one to check whether a string starts with a specified substring. 

Syntax: It takes a single argument, which is the substring we want to check whether the string starts with.

string.startsWith(searchString[, position])

Similar Reads

Approach 1: Using startWith method

The ‘searchString’ parameter is the substring that you want to search for at the beginning of the string. The ‘position’ parameter is an optional parameter that specifies the position in the string to start the search. If not specified, the search starts from the beginning of the string (position 0)....

Approach 2: Using Regular Expression (RegExp)

Regular expressions provide a flexible way to match patterns within strings. We can use a regular expression pattern to check if a string starts with another string....

Contact Us