Helge
Helge

Reputation: 833

Regexp to strip away wrapping DIV-tag

In certain cases the response from the server is wrapped in a DIV-tag like this:

<div id="marker-aab44ba9d64a41398ed97a251dfb938e-629">42</div>

The content of the tag might be whatever: A string, a number, a URL, a javascript array, a javascript object.

The format of the tag is always:

<div id="marker-[random string here]">content</div>

I'd like to use a regular expression to strip away the tag, how can I do this?

And remember: The response from the server might be just the content without the wrapping DIV, so the regexp should account for that.

Upvotes: 2

Views: 9736

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You could use anchors:

var res = str.replace(/^<div[^>]*>|<\/div>$/g, '');

If your content between div tags is in HTML, you can use this to be sure to remove only the divs you want:

var res = str.replace(/^<div[^>]*? id\s*=\s*["']?marker-[^>]+>([\S\s]*)<\/div>$/g, '\1');

Upvotes: 5

Helge
Helge

Reputation: 833

This should work:

function (string) {
    var match = string.match('<div id="marker-[^"]*">(.*)</div>');
    if(match) {
        return $(string).html(); 
    } else {
        return string; 
    }
};

:-)

Upvotes: 0

Related Questions