JavaScript check if the string starts with ^ and ends with $


In this post, we will learn about how to check if a string starts ^ and ends with $ with program examples. In regular expression two anchors characters are used, the first character is Cater (^) that is used at the beginning of the string, and the dollar($) at end of the string.

The anchors are used to match the position between, before, after characters. Let us understand with examples.

1. JavaScript check string start ^

In this example, we are checking for three input strings. First, check if inputStr starts with pattern ^Welcome which means the string starts with ^ and then string welcome.

Secondly, check if inputStr2 starts with pattern ^How the mean string starts with ^ and then string How.

Finally, check if inputStr3 with pattern ^Thanks that mean string start and then string Thanks.

let inputStr = "Welcome  to";
let inputStr2 = "How are you";
let inputStr3 = "Thanks for visiting"

console.log( /^Welcome/.test(inputStr) ); 
console.log( /^How/.test(inputStr2) ); 



2. JavaScript check string end with $

In this Javascript program example, Firstly we are checking if the string ends with devenum by using pattern devenum$

Secondly,we are checking if string end with Tutorial by using pattern devenum$.

let Str = "Hi Everyone devenum";
let inputStr2 = "Technology Tutorial";

console.log( /devenum$/.test(Str) ); 
console.log( /Tutorial$/.test(inputStr2) ); 



3. JavaScript check whole string start ^ and end with $

The anchors ^……$ together check if given string the full match the pattern. In this JavaScript program example, we are checking if the string is in given format nt:90 which means the string contains 2 characters before the colon and 2 digits after colon by using the regular expression /^[A-Za-z]{2}:[0-9]{2}$/.

The whole given string starts with 2 characters and ends with 2 digits before and after the colon are matching with regular expression. So it’s returning true.

let Str = "nt:90";
let Str2 = "kk:80";

let regexp = /^[A-Za-z]{2}:[0-9]{2}$/;
console.log( regexp.test(Str) );
console.log( regexp.test(Str2) );




In this post, we have learned in JavaScript, how to check string starts with ^ and end with $ by using anchors character Cater (^) and dollar($).