获取字符串中<body> </ body>的内容

apr*_*rea 3 html ajax jquery

我想做以下事情.

$("a").click(function (event) {

    event.preventDefault();

    $.get($(this).attr("href"), function(data) {

        $("html").html(data);

    });

});
Run Code Online (Sandbox Code Playgroud)

我希望所有超链接的行为进行ajax调用并检索html.

不幸的是,你不能简单地用你在ajax响应中收到的html替换当前的html.

只是如何能抓住什么是内<body> </body>Ajax响应的标签,这样我可以取代在现有的HTML体的内容.

编辑:<body>开始标记并不总是只是<body>它有时可能有一个类,例如

<body class="class1 class2">

Rob*_*sch 9

如果我理解正确,请使用正则表达式获取正文标记之间的内容.

$.get($(this).attr("href"), function(data) {
    var body=data.replace(/^.*?<body>(.*?)<\/body>.*?$/s,"$1");
    $("body").html(body);

});
Run Code Online (Sandbox Code Playgroud)

编辑

根据您在下面的评论,这里是一个匹配任何正文标记的更新,无论其属性如何:

$.get($(this).attr("href"), function(data) {
    var body=data.replace(/^.*?<body[^>]*>(.*?)<\/body>.*?$/i,"$1");
    $("body").html(body);

});
Run Code Online (Sandbox Code Playgroud)

正则表达式是:

^               match starting at beginning of string

.*?             ignore zero or more characters (non-greedy)

<body[^>]*>     match literal '<body' 
                    followed by zero or more chars other than '>'
                    followed by literal '>'

(               start capture

  .*?           zero or more characters (non-greedy)

)               end capture

<\/body>        match literal '</body>'

.*?             ignore zero or more characters (non-greedy)

$               to end of string
Run Code Online (Sandbox Code Playgroud)

添加'i'开关以匹配大写和小写.

请忽略我对's'开关的评论,在JavaScript中,所有RegExp默认都是单行,为了匹配多行模式,你添加'm'.(该死的Perl,在我写JavaScript时干扰我!:-)