2015-12-29 22 views
3

JSON结果:Hi,xxx,yy,,,welcome如何使用jquery替换json结果中的逗号?

我曾尝试以下:

var bfrreplace = ' Hi,xxx,yy,,,welcome';  
    bfrreplace.replace(/,/g, ' '); 

导致作为Hi xx yy welcome但我需要的结果为:Hi xxx yy ,welcome

,非常感谢。

+3

首先是'嗨,xxx,yy ,,, welcome'不是json,但似乎是一个字符串。 – Jai

回答

2

,我可以看到它是一个字符串不是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>

+0

谢谢..他的工作:) –

+0

欢迎@kesav – Jai

2

您可以使用简单的split()join()基于分隔符分割字符串,即,,然后过滤掉空字符串并连接数组元素以形成字符串。

var bfrreplace = ' Hi,xxx,yy,,,welcome'; 
 
bfrreplace = bfrreplace 
 
    .split(',') //Will create an array 
 
    .filter(function(n) { 
 
    return n != undefined && n.length > 0; //Filter out empty elements 
 
    }) 
 
    .join(','); //Return joined string 
 
snippet.log(bfrreplace)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>