admin管理员组

文章数量:1336293

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.

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.

Share Improve this question edited Jan 30, 2023 at 11:57 Xiddoc 3,6383 gold badges15 silver badges40 bronze badges asked Jun 17, 2013 at 13:29 HelgeHelge 8335 gold badges13 silver badges28 bronze badges 5
  • 1 it doesn't sound plicated, have you tried something yourself? – Michal Klouda Commented Jun 17, 2013 at 13:32
  • 2 Don't use regexp. Use DOM methods. For example: jsfiddle/v8S7Z . It depends on what you actually need and what can exactly be in the response – Ian Commented Jun 17, 2013 at 13:33
  • @ Lan, great answer. Please put answers in the answers field and not the ments. – Ro Yo Mi Commented Jun 17, 2013 at 14:07
  • Can your content between divs be html? – Casimir et Hippolyte Commented Jun 17, 2013 at 14:58
  • @Denomales Thanks. I like to suggest it in the ments first, when I'm not 100% sure what's needed. If I get good feedback, then I post an answer...which I just did :) – Ian Commented Jun 18, 2013 at 13:36
Add a ment  | 

2 Answers 2

Reset to default 5

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');

This should work:

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

:-)

本文标签: javascriptRegexp to strip away wrapping DIVtagStack Overflow