Pranav C Balan
Pranav C Balan

Reputation: 115222

I need match string in quotes

I need to match string within "" , I'm using following it's not working

var str='"hi" hello "abc\nddk" ef "gh"';

console.log(str.match(/(?=")[^"]*?(?=")/));

t's giving me output as

[]

I need output as

["hi", "abc\nddk", "gh"]

Update :

I can use regex "[^"]" to match string in quotes but I need to avoid the " from the result

Upvotes: 0

Views: 59

Answers (3)

Kevin Jantzer
Kevin Jantzer

Reputation: 9451

This should do the trick:

/(?| (")((?:\\"|[^"])+)\1 | (')((?:\\'|[^'])+)\1 )/xg

Demo

BTW: regex101.com is a great resource to use (which is where I got the regex above)

Update

The first one I posted works for PHP, here is one for JS

/"([^"\\]*(?:\\.[^"\\]*)*)"|\w+|'([^'\\]*(?:\\.[^'\\]*)*)'/g

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191739

Simplest way would be to do:

/"[^"]*?"/g

This will return an array with "hi", "abc\nddk" and "gh" and you can do something like piece.replace(/"/g, "") on individual pieces to get rid of the ". If you don't like that then rather than do a match you can do a search and don't replace

var matches = [];
str.replace(/"([^"]*?)"/g, function (_, match) {
    matches.push(match);
});

Upvotes: 3

Daniel Lizik
Daniel Lizik

Reputation: 3144

Maybe I read your question incorrectly but this is working for me

/\".+\"/gm

https://regex101.com/r/wF0yN4/1

Upvotes: 0

Related Questions