因此,我有一个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."这样的键/val,那么它将被转换为"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, '')删除了整个空格,甚至在引号中也是如此。我知道这可能是正确的结果,但我不知道如何只删除它以外的引号。我假设这个正则表达式可以跳过替换引号内的间距,但我对它一点也不熟悉。
发布于 2015-07-19 14:10:43
使用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"));
发布于 2015-07-19 14:14:41
试着利用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));
https://stackoverflow.com/questions/31502068
复制相似问题