Search code examples
javascripthtmlregexstrip

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.


Solution

  • This should work:

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

    :-)