Java Reference
In-Depth Information
One problem that the test string makes clear is that you want to replace the single‐quote mark with
a double only where it is used in pairs around speech, not when it is acting as an apostrophe, such as
in the word that's , or when it's part of someone's name, such as in O'Connerly .
Let's start by defining the regular expression. First, you know that it must include a single quote, as
shown in the following code:
var myRegExp = /'/;
However, as it is this would replace every single quote, which is not what you want.
Looking at the text, you should also notice that quotes are always at the start or end of a word—
that is, at a boundary. On first glance it might be easy to assume that it would be a word boundary.
However, don't forget that the ' is a non‐word character, so the boundary will be between it and
another non‐word character, such as a space. So the boundary will be a non-word boundary or, in
other words, \B .
Therefore, the character pattern you are looking for is either a non-word boundary followed by a
single quote or a single quote followed by a non-word boundary. The key is the “or,” for which you
use | in regular expressions. This leaves your regular expression as the following:
var myRegExp = /\B'|'\B/g;
This will match the pattern on the left of the | or the character pattern on the right. You want to
replace all the single quotes with double quotes, so the g has been added at the end, indicating that a
global match should take place.
replacing Single Quotes with Double Quotes
trY it out
Let's look at an example using the regular expression just defined:
<!DOCTYPE html>
 
<html lang="en">
<head>
<title>Chapter 6, Example 4</title>
</head>
<body>
<script>
var text = "He then said 'My Name is O'Connerly, yes " +
"that's right, O'Connerly'";
 
document.write("Original: " + text + "<br/>");
 
var myRegExp = /\B'|'\B/g;
text = text.replace(myRegExp, '"');
 
document.write("Corrected: " + text);
</script>
</body>
</html>
Search WWH ::




Custom Search