1

嗨,我是 javascript 的新手,所以我想知道如何删除括号内的单词并删除括号?我还想删除冒号之前的单词,然后用逗号替换括号,最后一个单词除外。例如,如果字符串包含:

language:chinese (29)parody:hyouka (73)character:fuyumi irisu (12)houtarou oreki (12)group:shuudan bouryoku (41)artist:murasaki syu (49)misc:schoolgirl (11)nakadashi (11)acting like a pet (6)

那么输出将变为

chinese,hyouka,fuyumi irisu,houtarou oreki,shuudan bouryoku,murasaki syu,schoolgirl,nakadashi,acting like a pet

我怎么能用javascript做到这一点?这是代码,它不起作用

var str = "language:chinese (29)parody:hyouka (73)character:fuyumi irisu (12)houtarou oreki (12)group:shuudan bouryoku (41)artist:murasaki syu (49)misc:schoolgirl (11)nakadashi (11)acting like a pet (6)";

var tags = str.replace(/\s*\(.*?\)\s*/g, ','));
final = tags.replace(/.*(?=:)/i, "");
alert(final);
4

1 回答 1

0

使用 [^)]+ 表示此处打开后没有右括号:

var str = "language:chinese (29)parody:hyouka (73)character:fuyumi irisu (12)houtarou oreki (12)group:shuudan bouryoku (41)artist:murasaki syu (49)misc:schoolgirl (11)nakadashi (11)acting like a pet (6)";  

var tags = str.replace(/\s?\([^\)]+\)/g, ',')
              .replace(/[^:]+:([^,]+),/g,'$1,')
              .replace(/,$/,'');
alert(tags);​

甚至很简单:

var tags = str.replace(/([^:]+:)?([^(]+)\s\([^\)]+\)/g,'$2,')
              .replace(/,$/,'');
于 2012-10-28T05:41:45.023 回答