Keerthi Kesav
Keerthi Kesav

Reputation: 53

How to replace the commas in the json result using jquery?

Json result : Hi,xxx,yy,,,welcome

I have tried as the following:

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

Which results as Hi xx yy welcome but I need the results as : Hi xxx yy ,welcome

With Thanks.

Upvotes: 3

Views: 270

Answers (2)

Jai
Jai

Reputation: 74738

As i can see it is a string not a json structure which requires to be a pair of keys and values like {key:value}.

In your issue you can use .match() with foreach loop call to create your required string 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>

But if you need a comma separated value then just use .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>

Upvotes: 2

Satpal
Satpal

Reputation: 133403

You can use simple split() and join() to split the string based on deliminator i.e. , then filter out empty strings and join the array elements to form the string.

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>

Upvotes: 2

Related Questions