用于将字符串拆分为数组并替换数组元素的正则表达式?

时间:2014-05-20 20:37:09

标签: javascript arrays regex string split

我希望从表单中获取标记并将它们保存到字符串数组中以进行循环。我希望标签上没有空格,#符号和逗号。

这几乎正常,但tagArraySplit[i].replace(/#/g, '');不会删除'#'..

var newTags = $( "#newTags" ).val();
console.log(newTags);
// regex split for one or more commas or spaces
// so that multiple consecutive spaces or a comma+space .. are not empty
var tagArraySplit = newTags.split(/[ ,]+/).filter(Boolean);
var tags = [];
for (i=0; i<tagArraySplit.length; i++)
{
    console.log(tagArraySplit[i]);
    tagArraySplit[i].trim;
    tagArraySplit[i].replace(/#/g, '');
    console.log('trimmed a tag');
    console.log(tagArraySplit[i]);
    tags.push(tagArraySplit[i]);
}
console.log(tags);

1 个答案:

答案 0 :(得分:3)

您需要存储String#replace方法的返回值:

tagArraySplit[i] = tagArraySplit[i].replace(/#/g, '');