在 coffeescript 中拆分为最终 space
split on final space in coffeescript
我有一个 name
变量,我通常可以期望它采用
的形式
John Smith
虽然无法验证,但有时会显示为
John Smith
或
John Jay Smith
我想最终得到两个变量,firstName
和 lastName
,并在最后一个 space 上进行拆分,所以我最终会得到
John Jay
& Smith
John
& Smith
John
& Smith
在决赛 space 上完成此拆分的最佳方法是什么?
您可以组合使用 string.lastIndexOf and string.slice。
它不会像沿某个字符拆分那样方便,但无论如何您都可以在 3 个语句中完成它,(1) 找到最后一个 space 的索引,(2) 获取之前的部分(3) 之后得到零件。
像这样的东西会起作用:
[firstname..., lastname] = "John Jay Smith".split(/ +/)
firstname = firstname.join(" ")
console.log firstname
console.log lastname
What's the best way to accomplish this split on a final space?
最后一个 space(或 spaces)可以使用否定的前瞻来定义,所以就分开:
[first, last] = "John Jay Smith".split(/\s+(?!.+ )/)
或者,regexp 可以轻松地为您分解它:
[, first, last] = "John Jay Smith".match(/^(.*)\s+(\S+)$/)
我有一个 name
变量,我通常可以期望它采用
John Smith
虽然无法验证,但有时会显示为
John Smith
或
John Jay Smith
我想最终得到两个变量,firstName
和 lastName
,并在最后一个 space 上进行拆分,所以我最终会得到
John Jay
& Smith
John
& Smith
John
& Smith
在决赛 space 上完成此拆分的最佳方法是什么?
您可以组合使用 string.lastIndexOf and string.slice。
它不会像沿某个字符拆分那样方便,但无论如何您都可以在 3 个语句中完成它,(1) 找到最后一个 space 的索引,(2) 获取之前的部分(3) 之后得到零件。
像这样的东西会起作用:
[firstname..., lastname] = "John Jay Smith".split(/ +/)
firstname = firstname.join(" ")
console.log firstname
console.log lastname
What's the best way to accomplish this split on a final space?
最后一个 space(或 spaces)可以使用否定的前瞻来定义,所以就分开:
[first, last] = "John Jay Smith".split(/\s+(?!.+ )/)
或者,regexp 可以轻松地为您分解它:
[, first, last] = "John Jay Smith".match(/^(.*)\s+(\S+)$/)