正则表达式删除空格和括号后缀

时间:2018-04-17 18:16:02

标签: javascript regex

我有几个输入字段标签:

let labels =  [
    "Foo Bar",
    "Baz (spam & eggs)",
    "More (junk here)"
];

我想要的结果是:

inputNames = [
    "FooBar",
    "Baz",
    "More"
]

在python中,我可以使用re.sub()替换基于正则表达式,但JS中的String.replace()方法可以这样做吗?你会怎么做?

4 个答案:

答案 0 :(得分:2)

您可以在JS中使用此正则表达式:



let labels =  [
    "Foo Bar",
    "Baz (spam & eggs)",
    "More (junk here)"
];

for (i=0; i<labels.length; i++) {
  labels[i] = labels[i].replace(/\s*(?:\([^)]*\))?/g, '');
}

console.log(labels);
&#13;
&#13;
&#13;

正则表达式/\s*(?:\([^)]*\))?/匹配1 +个空格,后跟方括号中的可选匹配。

答案 1 :(得分:1)

使用.indexOf(' (')查看字符串中是否存在' (',如果是,请删除substr()后面的任何内容(包括在内)

&#13;
&#13;
let labels =  [
     "Foo Bar",
    "Baz (spam & eggs)",
    "More (junk here)"
];

labels.forEach(function(e,i){
var until = e.indexOf(' (');
  if(until !== -1)
    labels[i] = e.substr(0, until);
});

console.log(labels)
&#13;
&#13;
&#13;

答案 2 :(得分:1)

我觉得这样的东西最具可读性:

let labels =  [
    "Foo Bar",
    "Baz (spam & eggs)",
    "More (junk here)",
    "(corner case)Foo(corner case) Jay"
];

for (i=0; i<labels.length; i++) {
  labels[i] = labels[i].replace(/ /g, "").replace(/\(.*?\)/g, "");
}

console.log(labels);

答案 3 :(得分:1)

首先删除所有空格,然后删除括号

inputNames = labels.map(e => e.replace(/ /g, '')).map(e => e.replace(/\(.*\)/g, ''));