Archive for April 6, 2007

JavaScript Regular Expression Special Characters: $ ^

Posted in JavaScript, Web, programming on April 6, 2007 by Joey

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);