admin管理员组

文章数量:1394526

Relative newer 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 ma:

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

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

Relative newer 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 ma:

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

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

Share Improve this question edited Sep 3, 2012 at 12:39 Michael Berkowski 271k47 gold badges450 silver badges394 bronze badges asked Sep 3, 2012 at 12:37 neilneil 1,3062 gold badges12 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Use:

cats = cats.replace(/:\s*,/g,", ");

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 bees [["Category A", "Keyword A"], ["Category B", ""], ["Category C", "Keyword B"]]

本文标签: stringJavascript Replace colon and comma charactersStack Overflow