使用 JavaScript 删除这些换行符
我一生都不知道如何删除这种奇怪的格式。这是 JSON.stringify(someObj)
之后发送给我的内容: http://jsbin.com/ohoto5/2/edit
单击预览,您将看到格式。我需要将其设置为一行,以便它可以进入 JSONP 响应(即 jsonp12345(...)
)。如果它是多行,则会触发语法错误。我已经尝试了我能想到的所有正则表达式组合,但没有任何方法可以删除这些行。甚至没有 /[\r\n\s\t]/gi
。唯一似乎删除它的是: /[\w\n]/gi
但是,问题是我丢失了所有单词!
有什么帮助吗?请不要修复 jQuery...我需要纯 JavaScript。
这是 Chrome 中的对象(图片):
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):
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在我看来,这应该可以做到:
jsFiddle 演示
似乎所有不必要的换行符都被删除了。
Looks to me that this should do it:
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.
放弃 JS 正则表达式后,我尝试了 PHP,并得到了第一次尝试:
其中缓存是上面我原来的 JSBin 链接中的 JSON。现在它返回:
有趣的是,JS 中完全相同的正则表达式并没有给出相同的结果 -_-
After giving up on JS regex I tried PHP and got it first try:
where the cache is the JSON in my original JSBin link above. Now it returns:
Funny how the exact same regex in JS doesn't give the same result -_-
CRLF 被编码为 \r\n,因此
str = str.replace(/(\r\n)/g, '');
应该可以完成这项工作。
CRLF is encoded as \r\n, so
str = str.replace(/(\r\n)/g, '');
should do the job.