Reputation: 1129
Suppose I have a string like 'there goes "something here", and "here" and I have "nothing else to say"'
.
I need a regex to retrieve exactly ['something here', 'here', 'nothing else to say']
. Note that the results aren't quote-escaped, this is because I don't want to make a second call for replace(/"/g, '')
on each match.
For reference, this:
'there goes "something here", and "here" and I have "nothing else to say"'.match(/".*?"/g)
Gives me this:
['"something here"', '"here"', '"nothing else to say"']
However, like I said, I dont want the results to be quote-scaped and make a replace
call on each result.
Upvotes: 1
Views: 459
Reputation: 2290
For when there should be a \w
after first quotation mark:
string = 'there goes "something here", and "here" and I have "nothing else to say"';
regexp = /(?<=")\w.*?(?=")/g
result = string.match(regexp);
console.log(result);
Accounting for there to be spacing between quotation mark and content:
let string = 'there goes " something here ", and "here" and I have "nothing else to say"';
function everyOther(string) {
let regexp = /(?<=").*?(?=")/g
let answerArray = [];
for (; ; ) {
if (regexp.lastIndex !== 0) {
regexp.lastIndex += 2;
}
let matchArr = regexp.exec(string);
if (regexp.lastIndex === 0) {
break;
}
let match = matchArr[0]
answerArray.push(match);
}
console.log(answerArray);
}
everyOther(string);
Upvotes: 1
Reputation: 203
By using some of the latest JS features
let reg = /"(.*?)"/gi;
let results = str.matchAll(reg);
// results - is not an array, but an iterable object
// convert results to an Array
results = Array.from(results);
// using map method to get second items from each array item
// which is a captured group
results = results.map(item => item[1]);
More info => javascript.info ::: matchAll with groups
Upvotes: 0
Reputation: 5257
This should work "([^"]*)"
and here is an example test:
https://regex101.com/r/CjK2fp/1
Upvotes: 1