是否有任何可能的方法来连接具有相同delimeter的拆分字符串?
例如,我有一个字符串,里面有句子
const str = "Edit the Expression & Text to see matches. Roll over matches or the expression for details? PCRE & JavaScript flavors of RegEx are supported! "
我想用句子分开。我就是这样。
str.split(/[.?!;]+s?/g)
我能用同样的delimeter把绳子连接起来吗?
str.split(/[.?!;]+s?/g).map(...).join(???)
谢谢!
您可以调用match
来获得所使用的分隔符数组,然后使用reduce
将数组连接回来并插入分隔符。
const str = `const str = "Edit the Expression & Text to see matches. Roll over matches or the expression for details? PCRE & JavaScript flavors of RegEx are supported! "`
const match = str.match(/[.?!;]+s?/g)
const result = str.split(/[.?!;]+s?/g).map(e => e).reduce((acc, curr, i) => (acc += curr + (match[i] || ""), acc), "")
console.log(result)
您可以将分隔符作为组进行拆分,并在根据需要更改第二部分后连接字符串。
const
str = "Edit the Expression & Text to see matches. Roll over matches or the expression for details? PCRE & JavaScript flavors of RegEx are supported! ",
result = str
.split(/([.?!;]+s*)/)
.map((s, i) => s && i % 2 === 0 ? `<stong>${s}<strong>` : s)
.join('');
console.log(result);
执行多个拆分/联接
let str = "Edit the Expression & Text to see matches. Roll over matches or the expression for details? PCRE & JavaScript flavors of RegEx are supported!"
const delim=['.','?','!',';']
delim.forEach(d=>{
console.log(str.split(new RegExp(`[${d}]+\s?`))) // showing what split does
str = str.split(new RegExp(`[${d}]+\s?`)).map(s=>s).join(d)
})