Learn how to extract text between double quotes from a string with JavaScript.
Let’s say you want to get some quoted text from a text block. Quotes are usually wrapped by double quotes (" "
). No problem, you can use JavaScript’s match()
method and some RegEx magic.
Here’s a text block (string value), containing one double-quoted sentence, that we assign to a variable called textWithQuote
:
const textWithQuote =
'One of my favorite quotes is "First we make our habits, then our habits make us". This quote is sometimes attributed to John Dryden, or other authors.'
Now let’s attach the match()
method to the variable and pass this somewhat gibberish looking argument /(?:"[^"]*"|^[^"]*$)/)[0].replace(/"/g, ""
(sorry):
const extractQuote = textWithQuote
.match(/(?:"[^"]*"|^[^"]*$)/)[0]
.replace(/"/g, "")
And print the result:
console.log(extractQuote)
// "First we make our habits, then our habits make us"
The reason we use [0]
is that otherwise the returned string is duplicated. By using [0]
we specify that we only want to return the first (one) result.
The reason we use the replace()
method (.replace(/"/g, "")
) is that otherwise, the returned result will contain excess quotes (because we’re returning quoted text inside a string which already has quotes).
An alternative method using split()
You can also get a double-quoted text value by using the split()
method:
const textWithQuote =
'One of my favorite quotes is "First we make our habits, then our habits make us". This quote is sometimes attributed to John Dryden, or other authors.'
console.log(textWithQuote.split('"')[1])
// "First we make our habits, then our habits make us"
In this case, we have to specify that we want to return the second result [1]
because [0]
will return One of my favorite quotes is
.
If you specify [2]
, you’ll get the text following right after the second "
double quote.
I’m not sure when to use either method and what the pros and cons are, as I’ve only recently started to dive deep on the topic of regular expressions.