How To Use Regular Expressions In JavaScript
RegExp.exec(string)
Applies the RegExp to the given string, and returns the match information.
1 |
var match = /s(amp)le/i.exec("Sample text") |
match then contains ["Sample","amp"]
RegExp.test(string)
Tests if the given string matches the Regexp, and returns true if matching, false if not.
1 |
var match = /sample/.test("Sample text") |
match then contains false
String.match(pattern)
Matches given string with the RegExp. With g flag returns an array containing the matches, without g flag returns just the first match or if no match is found returns null.
1 |
var str = "Watch out for the rock!".match(/r?or?/g) |
str then contains ["o","or","ro"]
String.search(pattern)
Matches RegExp with string and returns the index of the beginning of the match if found, -1 if not.
1 |
var ndx = "Watch out for the rock!".search(/for/) |
ndx then contains 10
String.replace(pattern,string)
Replaces matches with the given string, and returns the edited string.
1 |
var str = "Naomi said: My name is Naomi!".replace(/Naomi/g,'Eric') |
str then contains "Eric said: My name is Eric!"
String.split(pattern)
Cuts a string into an array, making cuts at matches.
1 |
var str = "I am Eric".split(/\s/g) |
str then contains ["I","am","Eric"]
Leave Your Comment
All fields marked with "*" are required.