从JSON对象中删除空白,但不能在引号内删除
Remove white space from JSON object, but not within quotes
所以我有一个input[type="text"]
,我想粘贴JSON对象作为配置。控制台的输出是完美的,所有内联没有任何修剪,但现在在input
我有很多间距。我想去掉空格并替换input
值。
$('#widget-json').on('input propertychange', function () {
var string = this.value.replace(/'s+/g, ''),
data = $.parseJSON( string );
$(this).val( string );
});
这几乎完成了工作,但它也删除了引号内的空格。因此,如果我有一个键/值,如"sentence": "Sure thing, good to go."
,这将被转换为"sentence":"Surething,goodtogo."
,而我想保留引号内的空格。
JSON对象示例
{
"widget-effect": 3,
"widget-opacity-color": "#C7C9CF",
"widget-opacity-slider": "50%",
"widget-opt-close": false,
"widget-opt-scroll": true,
"widget-opt-totop": true,
"widget-text": "Spacing required within quotes"
}
期望输出示例
{"widget-effect":3,"widget-opacity-color":"#C7C9CF","widget-opacity-slider":"50%","widget-opt-close":false,"widget-opt-scroll":true,"widget-opt-totop":true,"widget-text": "Spacing required within quotes"}
- 我试过了,
jQuery.trim( this.value )
,根本不起作用。 - 我试过了,
this.value.replace(/'s+/g, '')
,删除了整个空白,甚至在引号内。我知道这可能是正确的结果,但我不知道如何仅在引号外删除它。
我假设regex可以适合跳过替换引号内的空格,但我真的不熟悉它。
使用正则表达式替换操作符
var s = '"sentence": "Sure thing, good to go."';
alert(s.replace(/("[^"]*")|'s/g, "$1"))
上面的正则表达式实际上是做什么的?
-
("[^"]*")
捕获所有双引号块。因此,在上面,"sentence"
和"Sure thing ..."
被捕获(意味着这个特定的部分将被存储到索引1的临时缓冲区中)。 -
|
OR -
's
匹配剩余字符串中的所有空格字符。 替换部分中的 $1
是指第一个捕获组捕获的所有字符。因此,第一个捕获组中的字符被保留,匹配的空格被删除。
更新:
不幸的是,当您转义字符串值中的引号时,regex将中断并停止为剩余的键/值对删除空格
var stri = `"sentence ''"with escaped quotes''" should not break": "Sure thing, good to go."`;
alert(stri.replace(/("(?:''"|[^"])*")|'s/g, "$1"));
尝试使用JSON.stringify
$("#widget-json").on("input propertychange", function () {
// var string = this.value.replace(/'s+/g, ''),
var data = JSON.stringify($.parseJSON( this.value ));
$(this).val( data );
});
var data = {
"widget-effect": 3,
"widget-opacity-color": "#C7C9CF",
"widget-opacity-slider": "50%",
"widget-opt-close": false,
"widget-opt-scroll": true,
"widget-opt-totop": true,
"widget-text": "Spacing required within quotes"
};
document.write(JSON.stringify(data));
相关文章:
- JS可以在Chrome中工作,但不能在Firefox中工作
- WebRTC视频聊天可以在FF中使用,但不能在Chrome中使用
- jQuery Datepicker可以在Safari中工作,但不能在FF或Chrome中工作
- 三角库可以与firefox一起使用,但不能在Chrome中使用
- Highcharts可以从服务器加载数据,但不能更新
- 刷新GoogleMaps tile服务器可以使用JavaScript,但不能使用GWT
- node.js可以识别字符模式,但不能识别数字模式
- 如何在元素中处理鼠标事件,但不能在其子元素上处理
- Json到CSV下载,可以在chrome中工作,但不能在IE浏览器中工作
- jQuery$.post可以在chrome、safari中工作,但不能在FF中工作(声明成功回调函数未定义)
- Javascript可以在chrome中使用,但不能在其他浏览器中使用
- Iframe加载调整大小在Chrome中工作,但不能在IE或Firefox中工作
- Rails Production-可以工作,但不能编辑/删除/创建记录
- 能够在Highcharts中看到值,但不能看到图形
- Django,HTML,JS:<img src=“#">可以在HTML中工作,但不能在JS文件中工作
- 使用拉斐尔JS;在全局级别创建“论文” - 我可以创建多个论文,但不能删除它们
- 为什么 jQuery 在使用样式标签填充 iframe 时会删除正文和头部标签,但不能没有样式标签
- 从JSON对象中删除空白,但不能在引号内删除
- 只能添加dom元素,但不能删除它们
- Cookie可以存储,但不能删除