Tomarto
Tomarto

Reputation: 2755

RegExp match a single quoted text without quotes - JavaScript

I'm sorry if it is a confusing question. I was trying to find a way to do this but couldn't find it so, if it is a repeated question, my apologies!

I have a text something like this: something:"askjnqwe234"

I want to be able to get askjnqwe234 using a RegExp. You can notice I want to omit the quotes. I was trying this using /[^"]+(?=(" ")|"$)/g but it returns an array. I want a RegExt to return a single string, not an array.

I don't know if it's possible but I do not want to specify the position of the array; something like this:

var x = string.match(/[^"]+(?=(" ")|"$)/g)[0];

Thanks!

Upvotes: 2

Views: 5700

Answers (3)

MikeM
MikeM

Reputation: 13631

match and exec always return an array or null, so, assuming you have a single double-quoted value and no newlines in the string, you could use

var x;
var str = 'something:"askjnqwe234"';

x = str.replace( /^[^"]*"|".*/g, '' );
// "askjnqwe234"

Or, if you may have other quoted values in the string

x = str.replace( /.*?something:"([^"]*)".*/, '$1' );

where $1 refers to the substring captured by the sub-pattern [^"]* between the ().

Further explanation on request.

Notwithstanding the above, I recommend that you tolerate the array indexing and just use match.

Upvotes: 2

Ja͢ck
Ja͢ck

Reputation: 173562

You can capture the information inside quotes like this, assuming it matches:

var x = string.match(/something:"([^"]*)"/)[1];

The memory capture at index 1 is the part inside the double quotes.

If you're not sure it will match:

var match = string.match(/something:"([^"]*)"/);

if (match) {
    // use match[1] here
}

Upvotes: 1

Halcyon
Halcyon

Reputation: 57709

Try:

/"([^"]*)"/g

in English: look for " the match and record anything that isn't " till you see another "".

Upvotes: 6

Related Questions