0

I have a string that contains a JSON object. Problem is the object is being returned like this for some reason:

string (4345) "{ "blabla" : { "bleble" : "bloblo" } ...}"

I need to extract everything between the first and last quotation basicly so that I can then decode the object.

I tried this in javascript:

var myVar = myString.match(/\".+$\"/);

But it's not working. What's the appropriate RegEx for my problem?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
ReX357
  • 1,199
  • 3
  • 19
  • 43

4 Answers4

2

So you know that (in your example) myString has your JSONed thing? Why not do:

   var myVar = myString.substring(1, myString.length - 2);

If there's some other junk before or after your JSONed thing, I guess you could use the indexOf and lastIndexOf operations.

Also check out this question: Regex to validate JSON

In response to the question in the comment:

//So let's say we have this string
example = '"[ { "title": "event1", "start": "NOW", } ]"'
//So our example string has quote literals around the bits we want

//indexOf gives us the index of the " itself, so we should add one
//to get the character immediately after the "
first_nonquote_character = example.indexOf('"') + 1 

//lastIndexOf is fine as is, since substring doesn't include the character
//at the ending index
last_nonquote_character = example.lastIndexOf('"')

//So we can use the substring method of the string object and the
//indices we created to get what we want

string_we_want = example.substring(first_nonquote_character, last_nonquote_character)

//The value in string_we_want is
//[ { "title": "event1", "start": "NOW", } ]

Hope that helps. BTW if your JSON is actually coming back with the ', } ]"' at the end of it and that's not a typo, you'd probably want to do a string.replace(/, } ]"$/, '}]').

Community
  • 1
  • 1
Joe Bedurndurn
  • 186
  • 1
  • 5
  • Good idea on indexOf and lastIndexOf. Worked like a charm. Sometimes I just complicate things for nothing. – ReX357 Aug 31 '11 at 23:10
  • Do you mind pasting an example of how you used indexOf and lastIndexOf up the double quotes before and after the json. I am getting "[ { "title": "event1", "start": "NOW", } ]" when using JSN.stringify and I want to remove the quotes surrounding the json. thanks – brg May 31 '13 at 17:50
1

You just need to get the group submatch:

/"(.*)"/.exec(myString)[1]
rczajka
  • 1,810
  • 14
  • 13
0

Try this:

var newstr = oldstr.match(/"(.+)"/)[1];
yahermann
  • 1,539
  • 1
  • 12
  • 33
0

This regex worked for me (I tested it with Rubular):

/"(.+)"/

And you could use it like this:

var newString = oldString.replace(/"(.+)"/, "$1");

Where the parens are for capturing what's in between the quotation marks (because you didn't want them, right?).

Pontus Granström
  • 1,089
  • 8
  • 18