regexp 

Send to Kindle
home » snippets » javascript » regexp



Flags

Flag Property Description
g global Changes methods test() and exec() to start the search at lastIndex instead of the beginning of the string. Changes string.match to returns all matches and string.split to split at all matches.
i ignoreCase ignore case.
m multiline Changes ^ and $ to match at the beginning and end of a line. However, . still won't match across newlines. Use [\s\S] as an alternative.
y (ES6) sticky Changes exec and test to match at lastIndex instead of conducting a search. Finally!

Properties

Property Type RW Description
lastIndex int RW specifies the index at which to start the next search.
source string R the source text of the regexp object (without flags).
global bool R true if the RegExp was constructed with the global ("g") flag.
ignoreCase bool R true if the RegExp was constructed with the ignoreCase ("i") flag.
multiline bool R true if the RegExp was constructed with the multiline ("m") flag.
sticky bool R (ES6) true if the RegExp was constructed with the sticky ("y") flag.

Methods

Method Description
regex.exec(str) search for a match in a string. Returns an array of information.
regex.test(str) tests for a match in a string. Returns true or false.
string.match(regex) search for a match in a string. Returns an array of information or null on a mismatch.
string.search([regex]) tests for a match in a string. Returns the index of the match, or -1 if the search fails.
string.replace(regex/substr, newSubStr/function, [flags]) search for a match in a string, and replaces the matched substring with a replacement substring. See here for using a function
string.split([separator[, limit]]) uses a regular expression or a fixed string to break a string into an array of substrings.

HowTo

Make . match everything including newlines

There's no flag for this unfortunately. However you can use the character set [\s\S] instead to replace .. So, for example, /[\s\S]*/.test("abc\ndef\n123") == true.