Javascript Regular Expressions Position Characters

Introduction

Javascript Regular Expressions Position Characters specify either where the match should start or end or what will be on either side of the character pattern.

For example, you might want your pattern to exist at the start or end of a string or line, or you might want it to be between two words.

The following table lists some of the most common position characters and what they do:

Position Character
Description
^


The pattern must be at the start of the string, or if it's a multi-line string,
then at the beginning of a line. For multi-line text, set the multi-line flag when defining the
regular expression using /regex/m.
$


The pattern must be at the end of the string, or if it's a multi-line string,
then at the end of a line. For multi-line text, set the multi-line flag when defining the
regular expression using /regex/m.
\b

This matches a word boundary, which is essentially the point between a
word character and a non-word character.
\B
This matches a position that's not a word boundary.

For example, to make sure your pattern was at the start of a line, use the following:

^myPattern 

This would match an occurrence of myPattern if it was at the beginning of a line.

To match the same pattern, but at the end of a line, use the following:

myPattern$ 

The word-boundary special characters \b and \B do not match characters.

They matches the positions between characters.

To make the word boundaries of this string stand out, let's convert them to the | character:

let myString = "Hello world!, this is a test. 234 234 "; 
let myRegExp = /\b/g; 
myString = myString.replace(myRegExp, "|"); 
console.log(myString); /* w ww. j a v a 2  s  . co m*/

You can see that the position between any word character and any non-word character is a word boundary.

The boundary between the start or end of the string and a word character is considered to be a word boundary.

The end of this string is a full stop.

So the boundary between the full stop and the end of the string is a non-word boundary, and therefore no | has been inserted.

If you change the regular expression in the example, so that it replaces non-word boundaries as follows:

let myString = "Hello world!, this is a test. 234 234 "; 
let myRegExp = /\B/g; 
myString = myString.replace(myRegExp, "|"); 
console.log(myString); //from w w w  .  j  av a  2  s .c  o  m



PreviousNext

Related