简体   繁体   English

如何将Ajax数据响应转换为字符串?

[英]How to convert Ajax data response to string?

Original version: 原始版本:

<div>
    <p>
        <span>text</span>
    </p>
<div>

RegExp: 正则表达式:

$.get('/some.html', function(data) {
    alert(data.replace(/<p.*p>/gi, ''));
});

After RegExp: RegExp之后:

<div>
    <>
        <span>text</span>
    </>
<div>

What do I need to get: 我需要得到什么:

<div>

<div>

If you want to work with the returned html, then you shouldn't be doing that through regex. 如果你想使用返回的html,那么你不应该通过正则表达式来做到这一点。

I'm not completely sure I understand your question, but it looks like you are trying to remove the <p> elements from the result? 我不完全确定我理解你的问题,但看起来你试图从结果中删除<p>元素? You can work with the returned html with jQuery, something like 您可以使用jQuery处理返回的html,例如

$(data).remove('p');

Javascript has no dotall mode so your . Javascript没有dotall模式所以你的. does not match newline characters. 与换行符不匹配。

but you can try this 但你可以试试这个

$.get('/some.html', function(data) {
    alert(data.replace(/<p[\S\s]*?p>/gi, ''));
});

[\\S\\s] means match any non whitespace ( \\S ) or any whitespace ( \\s ) character. [\\S\\s]表示匹配任何非空格( \\S )或任何空格( \\s )字符。 the newline characters are included in the whitespace characters. 换行符包含在空白字符中。

The *? *? is a non greedy match, means it matches as less as possible. 是一种非贪婪的比赛,意味着它尽可能地匹配。

As soon as your tags are nested, you will run into problems when using regular expressions. 一旦嵌套了标记,使用正则表达式时就会遇到问题。 You have to be aware of that. 你必须意识到这一点。 Probably the solution from @fearofawhackplanet is the better choice. 可能来自@fearofawhackplanet的解决方案是更好的选择。

if i got you correctly then you need something like this...but it will make all div in your page as a blank div 如果我找到了你,那么你需要这样的东西......但它会使你页面中的所有div成为一个空白的div

 $('div').html('');

if you want remove specific div then give an id to that div and then do it like this.. 如果你想删除特定的div然后给该div的id,然后像这样做..

$(data).find('#divID').html(' ');

Javascript regexp don't match \\n with ".". Javascript正则表达式与\\ n匹配“。”。 And you specified //g flag. 你指定了// g标志。 in normaly, use [\\s\\S] in javascript. 在normaly中,在javascript中使用[\\ s \\ S]。

alert(data.replace(/<p[\s\S]*?p>/i, ''));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM