javascript - 仅在一个点拆分字符串

标签 javascript jquery regex split

我的脚本需要从破折号/连字符中拆分字符串。并将每一 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/

相关文章:

javascript - 编码 URIcomponent 非 utf-8 字符并相应解码它们的正确方法是什么?

javascript - 打开仅显示传递的打印机名称或 IP 的打印对话框?

javascript - 在追加中调用删除按钮

jquery - 从 href 属性以外的其他内容加载 colorbox 图像

regex - 匹配单词开头的任何子串

c# - 如果文本不在某些指定的 HTML 标记内,则替换文本

javascript - XUL 和 document.write()

javascript - 无限javascript while循环查询表

javascript - 在 jQuery Datatable 上获取空记录后如何隐藏加载图像

javascript - 您将如何使用正则表达式验证一串手机号码?