Alex Rivera | Logout

How can I get a substring located between 2 quotes?

Asked 2012-09-11T09:54:54.807
18

I have a string that looks like this: "the word you need is 'hello' ".

What's the best way to put 'hello' (but without the quotes) into a javascript variable? I imagine that the way to do this is with regex (which I know very little about) ?

Any help appreciated!

Edit
Report

1 Answer

1

If you want to avoid regular expressions then you can use .split("'") to split the string at single quotes , then use jquery.map() to return just the odd indexed substrings, ie. an array of all single-quoted substrings.

var str = "the word you need is 'hello'";
var singleQuoted = $.map(str.split("'"), function(substr, i) {
   return (i % 2) ? substr : null;
});

DEMO

CAUTION

This and other methods will get it wrong if one or more apostrophes (same as single quote) appear in the original string.

answered 2012-09-11T10:20:24.443

Your Answer