Dan*_*Boy 1 javascript regex jquery split
我的脚本我需要从短划线/连字符分割出一个字符串.并将每个部分分配给一个变量.
例:
Blue Oyster Cult - Don't Fear The Reaper
Jimi Hendrix - Come On (Let The Good Times Roll)
Molly Hatchet - Dreams I'll Never See
Run Code Online (Sandbox Code Playgroud)
我认为正则表达式可以做到这一点,[\-]+但我正在寻找一种方法,它不会超过两个变量.所以无论它采用什么字符串,结果必须只有两个部分.我认为最好的方法是只考虑-字符串中的第一个(连字符).
知道怎么做到这一点?
提前致谢.
简单地做 .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"Run Code Online (Sandbox Code Playgroud)
PS:请注意,上面我.trim()只是为了摆脱字符串包装空白的正则表达式简单和演示!...虽然如果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"Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |