We ' ll capture groups of characters we wish to match, use quantifiers with those groups, and use references to those groups In String.prototype.replace.
Let's see we had set of similar string starting with ' foo '
var str = ' foobar fooboo foobaz ';
And what we want to do are replace any ' foobar ' & ' Foobaz ' with ' **foobar** ' && ' **foobaz** ':
var str = ' foobar fooboo foobaz '; var regex =/foo (bar|baz)/' **foo$ * ')); /* " **foobar** fooboo **foobaz**"* /
$, capture the Gourp and save into memory.
Another example:
Let's say we get the area code for each number.
var str = ' 800-456-7890(555) 456-78904564567890 ';
The result for the input should is ' 800, 555, 456 '.
Todo this,
First:divide those number into xxx xxx xxxx, 3 3 4 group:
var regex =/\d{3}\d{3}\d{4}/g;
Second:now the one match, because, between group, there can be ' empty space ' or '-':
Use:
\s // for space- // for -[\s-] // for select one element Inside [], so \s or-// 0 or more
So:
var regex =/\d{3}[\s-]? \D{3}[\s-]? \d{4}/g;
Third:we need to match ():
\(? // match (: can be 0 or 1\)? // match): can be 0 or 1
So:
var regex =/\ (? \D{3}\)? [\s-]?\d{3}[\s-]?\d{4}/g;
Last:we need to capture the first 3 digital number group. Use (XXX):
var regex =/\ (? \(d{3})\)? [\s-]?\d{3}[\s-]?\d{4}/g;
Then console.log the captured group:
$ ')/*"area Code:800area code:555area code:456"* /
Example 3:
Re-format the number to xxx-xxx-xxxx:
var str = ' 800-456-7890(555) 456-78904564567890'; var regex =/\ (? ( \d{3})? [\s-]? (\d{3}) [\s-]? (\d{4})/g; var res = str.replace (regex, "$1-$2-$3"); Console.log (res); /* "800-456-7890555-456-7890456-456-7890" */
------------------
As we said, (XX) actually capture the group value and store into the memory, if you don ' t store tha reference into the mem Ory, can do:
(?:/// ?: Won ' t store the referenceinto the memory ' area code: $ ')) /* "Area code: $1area Code: $1area Code: $" */
[Regular Expressions] Find Groups of characters, and?: