Plummer
Plummer

Reputation: 6688

regex extract text inside quotes

In Javascript, I'm storing found regex entries to a JSON array. The stored entries contain the encapsulating single quotes--but I don't want them to.

The string I'm checking looks like this:

{{ 'Foo' | i18n:['bar'] }}

The regex expression looks like so:

('[^'\\]*(?:\\.[^'\\]*)*')

This will return 'foo' and 'bar' when I just want it to return foo and bar.

I have the ability to just do a .replace(/'/g. ''); but that doesn't help if there's an escaped single quote like so:

{{ 'foo\'s' | i18n }}

Upvotes: 0

Views: 127

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

Use capturing group to capture the previous charcater which must not be a backslash.

.replace(/(^|[^\\])'/g, '$1');

$1 refers the charcaters which are captured by the first group.

Example:

var s = "{{ 'foo\\'s' | i18n }}"
alert(s.replace(/(^|[^\\])'/g, '$1'))

Upvotes: 1

Related Questions