Created
March 20, 2018 10:07
-
-
Save jonurry/34d029cf5b83fd4b0f2012a4684bd1ed to your computer and use it in GitHub Desktop.
9.2 Quoting style (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let text = "'I'm the cook,' he said, 'it's my job.'"; | |
// ' at begining of string or | |
// ' after non-word character or | |
// ' before non-word character or | |
// ' at and of string | |
console.log(text.replace(/^'|(\W)'|'(\W)|'$\b/g, "$1\"$2")); | |
// → "I'm the cook," he said, "it's my job." |
Hints
The most obvious solution is to only replace quotes with a non-word character on at least one side. Something like /\W'|'\W/
. But you also have to take the start and end of the line into account.
In addition, you must ensure that the replacement also includes the characters that were matched by the \W
pattern so that those are not dropped. This can be done by wrapping them in parentheses and including their groups in the replacement string ($1, $2)
. Groups that are not matched will be replaced by nothing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
9.2 Quoting Style
Imagine you have written a story and used single quotation marks throughout to mark pieces of dialogue. Now you want to replace all the dialogue quotes with double quotes while keeping the single quotes used in contractions like aren’t.
Think of a pattern that distinguishes these two kinds of quote usage and craft a call to the
replace
method that does the proper replacement.