user3386779
user3386779

Reputation: 7185

Replace all occurrences of ',' to space in a string

I want to replace all the occurence of ',' to ' ' and '{' to ' ' and ' }' to ' '.

By using replace, I can only replace the first occurrence of ',' and I want to replace all occurrences.

 const summary_data=[{Geo: "US West", MeetingHash: "Hold/Uncategorized", count: 65},
    {Geo: "NSU", MeetingHash: "Hold/Uncategorized", count: 9}, 
     {Geo: "US East", MeetingHash: "Hold/Uncategorized", count: 3}];
  
       var str="";
        $.each(summary_data, function (key, entry) {
           str += JSON.stringify(entry) .replace(","," ") + "\n";
         });
            console.log(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Views: 258

Answers (6)

Mamdouh Saeed
Mamdouh Saeed

Reputation: 2324

string.replace(searchvalue, newvalue) where searchvalue can be string or RegExp, and the below example to perform a global replacement.

JSON.stringify(entry) 
  .replace(/\,/g, " ") // replace comma's with spaces
  .replace(/\s+/g, " ").trim() //remove extra spaces with only one and trim
  .replace(/[\{\}]/g, "") //To replace multiple 

Upvotes: 1

phuzi
phuzi

Reputation: 13060

From the String.prototype.replace() docs at MDN

... If pattern is a string, only the first occurrence will be replaced.

To get around this limitation either use replaceAll() or a regular expression i.e. replace(/,/g, ' ')

Upvotes: 1

AttemptedMastery
AttemptedMastery

Reputation: 768

let str = JSON.stringify(summary_data).split(',').join(' ').split('{').join(' ').split('}').join('')

No regex answer

Upvotes: 1

Evgeny Klimenchenko
Evgeny Klimenchenko

Reputation: 1194

Hey replace accepts regex and you can put global flag on it like this:

replace(/,/g, " ")

This will replace all occurrences of "," with " "

Upvotes: 2

Nanoo
Nanoo

Reputation: 903

Try this:

var exampleStr = "{example, string}";

// Returns " example  string "
exampleStr.replace(/,/g, " ").replace(/{/g, " ").replace(/}/g, " ");

// Returns "example string"
exampleStr.replace(/,/g, "").replace(/{/g, "").replace(/}/g, "");

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89344

You need to create a regular expression with the global modifier. Use the pipe (|) to match either a comma or curly brace.

str += JSON.stringify(entry) .replace(/,|\{|\}/g," ") + "\n";

 const summary_data=[{Geo: "US West", MeetingHash: "Hold/Uncategorized", count: 65},
    {Geo: "NSU", MeetingHash: "Hold/Uncategorized", count: 9}, 
     {Geo: "US East", MeetingHash: "Hold/Uncategorized", count: 3}];
  
       var str="";
        $.each(summary_data, function (key, entry) {
           str += JSON.stringify(entry) .replace(/,|\{|\}/g," ") + "\n";
         });
            console.log(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions