开发者

Remove These Line Breaks with JavaScript

开发者 https://www.devze.com 2023-03-08 04:20 出处:网络
For the life of me I can\'t figure out how to remove this weird formatting. This is what is getting sent to me after a JSON.stringify(someObj): http://jsbin.com/ohoto5/2/edit

For the life of me I can't figure out how to remove this weird formatting. This is what is getting sent to me after a JSON.stringify(someObj): http://jsbin.com/ohoto5/2/edit

Click preview and you'll see the formatting. I need that to be one line so that it can go in a JSONP response ( i.e. jsonp12345(...) ). If it's multiple lines it will trigger a syntax error. I've tried every regex combo i can think of and nothing removes the lines. No /[\r\n\s\t]/gi even. The only thing that seems to remove it is: /[\w\n]/gi however, the issue is that i lose all the words!

Any help? Please no jQuery fixes... I'm in need of pure JavaScript.

Here is the object in Chrome (pic): 开发者_如何学编程

Remove These Line Breaks with JavaScript


Looks to me that this should do it:

s.replace(/[\r\n]/g, '')

jsFiddle Demo

Seems like every unnecessary line-break is removed.


Difficult to tell what is needed, however there are many differences between what browsers recognise as whitespace, consider setting precisely what characters you wish to match, e.g.

// List of characters matched as white space 
var whiteSpace = '\u0009\u000a\u000b\u000c\u000d\u0020\u00a0' + 
                 '\u1680\u180e\u2000\u2001\u2002\u2003\u2004' + 
                 '\u2005\u2006\u2007\u2008\u2009\u200a\u200b' + 
                 '\u2028\u2029\u202f\u205f\u3000'; 
var re = new RegExp('[' + whiteSpace + ']+', 'g');

var x = 'lots and  lots     of    space     ';

alert(x.replace(re, ' ').replace(/ +/,' '));


After giving up on JS regex I tried PHP and got it first try:

preg_replace('/\s\s+/', ' ', $referrer['cache'])

where the cache is the JSON in my original JSBin link above. Now it returns:

callback([{"LatLng":{"Ba":45.531124,"Ca":-122.68374699999998},"InfoWindow":" <address>1125 NW 12th Ave, Portland, OR</address> <p>My first apartment</p> ","originalAddress":"1125 NW 12th Ave, Portland, OR"},{"LatLng":{"Ba":45.5138621,"Ca":-122.67767300000003},"InfoWindow":" <address>1330 SW 3rd Ave, Portland, OR</address> <p>My 2nd apartment</p> ","originalAddress":"1330 SW 3rd Ave, Portland, OR"},{"LatLng":{"Ba":45.748955,"Ca":-122.47959000000003},"InfoWindow":" <address>17501 NE 188th Ct, Brush Prairie, WA</address> <p>The first place I lived by my own</p> ","originalAddress":"17501 NE 188th Ct, Brush Prairie, WA"},{"LatLng":{"Ba":45.756944,"Ca":-122.43575800000002},"InfoWindow":" <address>18607 NE Erickson Rd, Brush Prairie, WA</address> <p>Last place I lived with my parents</p> ","originalAddress":"18607 NE Erickson Rd, Brush Prairie, WA"}])

Funny how the exact same regex in JS doesn't give the same result -_-


CRLF is encoded as \r\n, so

str = str.replace(/(\r\n)/g, '');

should do the job.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号