2

How can I extract the value between the tags (49% in message) using Javascript? I will first parse the JSON with JSON.parse.

{
      "id": "189180337778229046", 
      "from": {
        "name": "My FB page", 
        "category": "Automobiles and parts", 
        "id": "189180337778229046"
      }, 
      "subject": "A good deal", 
      "message": "<p><strong>49%</strong></p><p>This is a good deal for you.</p>", 
      "icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yY/r/d1gBp2bDGEuh.gif", 
      "created_time": "2011-11-02T10:49:56+0000", 
      "updated_time": "2011-11-02T10:49:56+0000"
    }

3 Answers 3

3

A simple RegExp will do. Assume obj to hold the value of the parsed JSON string:

var percent = obj.message.match(/<strong>(.*?)<\/strong>/i)[1]; //Returns 49%
Sign up to request clarification or add additional context in comments.

3 Comments

Will fail due to incomplete escaping (should be <//strong>).
I tried both <//strong> and </strong> and it fails (invalid flag).
@JonathanClark Inside an RegExp, characters have to be escaped using `. So, <\/strong>`. Updated answer to correct mistake.
1

Easiest will be to use jQuery which looks like you're already using: (as JSON.parse is part of it)

var myValue = $(data.message).find("strong").eq(0).text();

2 Comments

Are you suggesting to create a new jQuery/DOM tree, so that jQuery methods can be used to perform a simple string operation? O_o
Yes, it's both more readable and flexible. The "price" for this is really minor.
0

You can do :

var pattern = /([0-9]+%)/gi;
var result = obj.message.match(pattern);

This will only match integer numbers though..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.