4

Relative newcomer to Javascript and a bit stuck with the following so would greatly appreciate some help...

I have a string made up of a list of categories and keywords which might appear like:

Category A:Keyword A, Category B:, Category C: Keyword B

The problem is displaying a category when there is no keyword - how can I do a Find and Replace to swap instances of :, with just ,?

I already use the following to insert a space after the comma:

cats = cats.replace(/,/g,", ");

but copying and modifying with the extra colon seems to break it...

Michael Berkowski
  • 260,803
  • 45
  • 432
  • 377
neil
  • 1,136
  • 1
  • 10
  • 19

2 Answers2

6

Use:

cats = cats.replace(/:\s*,/g,", ");
xdazz
  • 154,648
  • 35
  • 237
  • 264
1

I think you should use arrays:

var arr="Category A:Keyword A, Category B:, Category C:Keyword B".split(', ');
for(var i=0;i<arr.length;i++){
   arr[i]=arr[i].split(':');
}

Then, arr becomes [["Category A", "Keyword A"], ["Category B", ""], ["Category C", "Keyword B"]]