RegExp Boundaries
- turned_in_notBoundaries
- ^x
- x$
- \b
- \B
- To run below examples, try it inside
<script>
tag, in a basic html file
^x
It matches x at the beginning of whole string & if 'm' flag is used then matches x at the beginning of first line, if 'mg' flag used then matches x at the beginning of every line
For example :
var str="good morning
my friend";
var pattern=/^../mg;
alert(str.match(pattern));
// Output: go,my
Matches:
good morning
my friend
Comment : Check first 2 letters of every line in string
x$
It matches x at the end of whole string & if 'm' flag is used then matches x at the end of first line, if 'mg' flag used then matches x at the end of every line
For example :
var str="good morning
my friend";
var pattern=/..$/mg;
alert(str.match(pattern));
// Output: ng,nd
Matches:
good morning
my friend
Comment : Check last 2 letters of every line in string
\b
It matches only if, before/after of x is not of the same type '\w' = [0-9a-ZA-Z_] or '\W' = [^0-9a-ZA-Z_]
\bx : x can be any \w or \W where letter just before x is not of the same type \w or \Wx\b : x can be any \w or \W where letter just after x is not of the same type \w or \W
Example for \bx:
var str="goood food today";
var pattern=/[gft]o/g;
alert(str.match(pattern));
// Output: go,fo,to
Matches: goood food today
Comment : Check letter just before go,fo,to in the string, it's not of the same type \w
Example for x\b:
var str="goood food+ today";
var pattern=/.[dy]/g;
alert(str.match(pattern));
// Output: od,od,ay
Matches: good food+ today
Comment : Check letter just after od,od,ay in the string, it's not of the same type \w
\B
It matches only if, before/after of x is of the same type '\w' = [0-9a-ZA-Z_] or '\W' = [^0-9a-ZA-Z_]
\Bx : x can be any \w or \W where letter just before x is of same type \w or \Wx\B : x can be any \w or \W where letter just after x is of same type \w or \W
Example for \Bx:
var str="books are good friend";
var pattern=/Boo./g;
alert(str.match(pattern));
// Output: ook,ood
Matches: books are good friend
Comment : Check letter just before ook & ood in the string, it's of same type \w
Example for x\B:
var str="books are good friend";
var pattern=/oo.B/g;
alert(str.match(pattern));
// Output: ook
Matches: books are good friend
Comment : Check letter just after ook in the string, it's of same type \w