简体   繁体   中英

Javascript: Replace colon and comma characters

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...

使用:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM