JSON結果:Hi,xxx,yy,,,welcome
如何使用jquery替換json結果中的逗號?
我曾嘗試以下:
var bfrreplace = ' Hi,xxx,yy,,,welcome';
bfrreplace.replace(/,/g, ' ');
導致作爲Hi xx yy welcome
但我需要的結果爲:Hi xxx yy ,welcome
,非常感謝。
JSON結果:Hi,xxx,yy,,,welcome
如何使用jquery替換json結果中的逗號?
我曾嘗試以下:
var bfrreplace = ' Hi,xxx,yy,,,welcome';
bfrreplace.replace(/,/g, ' ');
導致作爲Hi xx yy welcome
但我需要的結果爲: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>
謝謝..他的工作:) –
歡迎@kesav – Jai
您可以使用簡單的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>
首先是'嗨,xxx,yy ,,, welcome'不是json,但似乎是一個字符串。 – Jai