JavaScript - Regular Expression

javascript

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
https://www.sitepoint.com/expressions-javascript/
http://kourge.net/projects/regexp-unicode-block
http://dustindiaz.com/regular-expression-back-matching
http://dustindiaz.com/regex-brain-teaser-part-ii

Basic usage and common cases
Flags
Using .search
Using .split
Using .exec
Using .match
Using .test
Using .replace
The sticky flag
Regular expression and Unicode characters
Finding successive matches or looping
Extending RegExp

How can we search a string for a pattern?

if (str.search(/abc/) > -1) {
}
var regex = new RegExp("\\b" + "abc" + "\\b");
if (str.search(regex) > -1) {
}

What is the literal format?

The literal format is specified using the slash:

if (str.search(/abc/) > -1) {
}

How to use the RegExp constructor?

When using the RegExp constructor, and if we are using double quotes, make sure that we double the escape (\) character as well:

var regex = new RegExp("\\b" + "abc" + "\\b");
if (str.search(regex) > -1) {
}

This is because the \ character is considered as an escape character when inside a string. If we use single quotes, we do not have to double the \ character.

When should we use the literal format and when should we use the RegExp constructor?

The RegExp constructor is handy when we do not know what to search for ahead of time (the pattern that we need to search for must be dynamically determined at run-time somehow based on other criteria).

How can we specify flags when using the literal format?

if (str.search(/abc/i) > -1) {
}

How can we specify flags when using the RegExp constructor?

We can specify the flags using the second parameters of the RegExp constructor:

var results = new RegExp('[\\?&]' + name + '=([^&#]*)', 'i').exec(window.location.href);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License