Swapping Words in a String Using Capturing Parentheses

 Swapping Words in a String Using Capturing Parentheses


You want to accept an input string with first and last name, and swap the names so the last name is first.


Use capturing parentheses and a regular expression to find and remember the two names
in the string, and reverse them:

var name = "Abe Lincoln";
var re = /^(\w+)\s(\w+)$/;
var newname = name.replace(re,"$2, $1");


Capturing parentheses allow us to not only match specific patterns in a string, but to
reference the matched substrings at a later time. The matched substrings are referenced
numerically, from left to right, as represented by $1 and $2 in the replace() method.

In the solution, the regular expression matches two words separated by a space. Cap‐
turing parentheses were used with both words, so the first name is accessible using $1,
the last name with $2.

The capturing parentheses aren’t the only special characters available with replace().

The second pattern, which reinserts the matched substring, can be used to provide a
simplified version of the Example 1-1 application shown in Recipe 1.6. That example
found and provided markup and CSS to highlight the matched substring. It used a loop
to find and replace all entries, but in Example 1-2 we’ll use replace() with the matched
substring special pattern ($&).

Using String.replace and special pattern to find and highlight text in astring

<!DOCTYPE html>
<title>Searching for strings</title>
 background-color: #ff0;
 <form id="textsearch">
 <textarea id="incoming" cols="100" rows="10">
 Search pattern: <input id="pattern" type="text" />
 <button id="searchSubmit">Search for pattern</button>
 <div id="searchResult"></div>
 document.getElementById("searchSubmit").onclick=function() {
 // get pattern
 var pattern = document.getElementById("pattern").value;
 var re = new RegExp(pattern,"g");
 // get string
 var searchString = document.getElementById("incoming").value;
 // replace
 var resultString = searchString.replace(re,"<span class='found'>$&</span>");
 // insert into page
 document.getElementById("searchResult").innerHTML = resultString;
</html> < span style="font-family: "arial" , "helvetica" , sans-serif;">
The captured text can also be accessed via the RegExp object using this exec() method. Let’s return to the  solution code, this time using exec():

var name = "Abe Lincoln";
var re = /^(\w+)\s(\w+)$/;
var result = re.exec(name);
var newname = result[2] + ", " + result[1];

This approach is handy if you want to access the capturing parentheses values, but
without having to use them within a string replacement.


Post a Comment