Javascript Regex Basic


To perform a string search using a regular expression literal:

if ( > -1) {

To perform a string search using the RegExp class:

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

Notice that, in the above code, we must use double-backslash to represent
a word boundary.  We could have use "\\babc\\b" but we separate it out into 
three parts and concatenate them together to show that we can dynamically 
create the RegExp.

The following expressions create the same regular expression:
new RegExp('ab+c', 'i');
new RegExp(/ab+c/, 'i');

To swap the two words:

var re = /(\w+)\s(\w+)/;
var str = 'John Smith';
var newstr = str.replace(re, '$2, $1');

To split a string of text by a regular expression:

var text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end';
var lines = text.split(/\r\n|\r|\n/);

To extracting sub-domain name from URL:

var url = '';
console.log(/[^.]+/.exec(url)[0].substr(7)); // logs 'xxx'

The above code look for all characters that is not a dot, essentially the 'http://xxx' 
and then invoke substr(7) to remove the 'http://' part.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License