我的脚本需要从破折号/连字符中拆分字符串。并将每一 block 分配给一个变量。
示例:
Blue Oyster Cult - Don't Fear The Reaper
Jimi Hendrix - Come On (Let The Good Times Roll)
Molly Hatchet - Dreams I'll Never See
我认为正则表达式可以用 [\-]+
来实现,但我正在寻找一种方法,它不会产生两个以上的变量。
因此,无论需要什么字符串,结果都必须只有两部分。我认为最好的方法是只考虑字符串中的第一个 -
(连字符)。
知道如何实现吗?
提前致谢。
最佳答案
只需执行 .split(/-(.+)/)
按 -(.+)
拆分匹配组 (.+)
将帮助您完整地获得所需的第二组 - 因为 .+
将消耗第一个 -
之后的所有字符,直到行尾:
var text = "Hello world - This is super - easy and cool";
var parts = text.split(/-(.+)/);
console.log( parts[0].trim() ); // "Hello world"
console.log( parts[1].trim() ); // "This is super - easy and cool"
P.S:请注意,上面我使用 .trim()
只是为了去除字符串包装空格以简化正则表达式和 demo!... 虽然如果 parts[1]
什么都不返回 (undefined
) 你会得到一个错误。因此,明智地使用 - 或扩展正则表达式以考虑分隔符 -
前后的可选空格和 \s?
var text = "Hello world - This is super - easy and cool";
var parts = text.split(/\s?-\s?(.+)/);
console.log( parts[0] ); // "Hello world"
console.log( parts[1] ); // "This is super - easy and cool"
关于javascript - 仅在一个点拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43378197/