Java Reference
In-Depth Information
Let's start by defi ning 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 fi rst 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.
Try It Out Replacing Single Quotes with Double Quotes
Let's look at an example using the regular expression just defi ned.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>example</title>
<script type=”text/JavaScript”>
function replaceQuote(textAreaControl)
{
var myText = textAreaControl.value;
var myRegExp = /\B'|'\B/g;
myText = myText.replace(myRegExp,'“');
textAreaControl.value = myText;
}
</script>
</head>
<body>
<form name=”form1”>
<textarea rows=”20” cols=”40” name=”textarea1”>
'Hello World' said Mr O'Connerly.
He then said 'My Name is O'Connerly, yes that's right, O'Connerly'.
</textarea>
<br>
<input type=”button” VALUE=”Replace Single Quotes” name=”buttonSplit”
onclick=”replaceQuote(document.form1.textarea1)“>
</form>
</body>
</html>
Search WWH ::




Custom Search