JavaScript Regular Expression Special Characters: $ ^

The ‘^’ and ‘$’ characters are crucial in JavaScript Regular Expressions. They can be used to specify how a tested string must begin or end.

The ‘^’ character matches the beginning of a string. The code /^j/ will return true for any string that begins with ‘j’ and false for any string that begins with a character other than ‘j’:

//Will return true
var IsFound = /^j/.test('joey');
alert (IsFound);

//Will return false
var IsFound = /^d/.test('joey');
alert (IsFound);

The ‘$’ character matches the end of a string. The code /y$/ will return true for any string that ends with ‘y’ and false for any string that begins with a character other than ‘y’:

//Will return true
var IsFound = /y$/.test('joey');
alert (IsFound);

//Will return false
var IsFound = /d$/.test('joey');
alert (IsFound);

3 Responses

  1. How i can validate forward slash(/) using javascript validator

    Thanks in advance,
    Mohan

  2. Mohan,
    Please try the following:
    document.write(/\//.test('this string has a / in it'));

  3. Im trying to search a textarea multi-line for a specific regular expression. If the return is false, i need to do a replace, matching the negation of my regular expression, to delete the wrong lines. How can i do this?

Leave a Reply