Json 结果:Hi,xxx,yy,,,欢迎
我尝试过如下:
var bfrreplace = ' Hi,xxx,yy,,,welcome';
bfrreplace.replace(/,/g, ' ');
结果为Hi xx yywelcome
,但我需要结果为:Hi xxx yy,welcome
谢谢。
最佳答案
正如我所看到的,它是一个字符串,而不是一个 json 结构,它需要是一对键和值,如 {key:value}
。
在您的问题中,您可以将 .match()
与 foreach
循环调用一起使用来创建所需的字符串 Hi xxx yy ,welcome
:
var bfrreplace = ' Hi,xxx,yy,,,welcome', // the string
arr = bfrreplace.match(/([a-z0-9A-Z])+/g), // .match(regex) to create an array
newStr=''; // new string to create as per requirement.
[].forEach.call(arr, function(s, i) { // loop over the created array
newStr += (i == arr.length - 1) ? " ," + s : " " + s; // adds a comma to the last value
});
document.querySelector('pre').innerHTML = newStr; // finally use the new String.
<pre></pre>
但是如果您需要逗号分隔值,则只需使用 .match(regex).join(', ')
:
var bfrreplace = ' Hi,xxx,yy,,,welcome', // the string
str = bfrreplace.match(/([a-z0-9A-Z])+/g).join(','); // .match(regex) to create an array
document.querySelector('pre').innerHTML = str; // finally use the new String.
<pre></pre>
关于jquery - 如何使用jquery替换json结果中的逗号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34506437/