JavaScript正则表达式替换非单词和空格不起作用

javascript regex replace nonwords and spaces does not work?

本文关键字:空格 不起作用 单词 正则表达式 替换 JavaScript      更新时间:2023-09-26
var st = "Dream Theater A Change of Seasons (EP) (1995)";
var searchTerm = st.replace("/['s'W]+/g", "+");

Dream Theater A Change of Seasons EP 1995

但我想成为
Dream+Theater+A+Change+of+Seasons+EP+1995+

你需要:

var searchTerm = st.replace(/['s'W]+/g, "+");

没有引号。

试试

st.replace(/'s/g, "+");

它只是用+替换每个空格字符。 另请注意,我删除了正则表达式周围的引号——你想要一个正则表达式,而不是一个字符串。

编辑 - 刚刚尝试

st.replace(/['s'W]+/g, "+"); // no quotes around the regex

这给了你最后的+。 所以真正的问题是,当你想要传递一个实际的正则表达式引用时,你正在传递一个字符串。

var searchTerm = st.replace(/['s'W]+/g, '+');