我知道有几种方法可以在jQuery中拆分数组,但我有一个特例:如果我有这两个字符串:
"G09.4 What"
"A04.3 A new Code"
Run Code Online (Sandbox Code Playgroud)
当我分裂首先' '我可以简单地选择与前面的代码[0]会是什么G09.4.当我打电话给[1]我时,我会得到文字:What
但是当我用第二个字符串做同样的事情时,我会[1] A想要检索A new Code.
那么如何为每个字符串检索代码和单独的文本?
Ron*_*Dex 22
使用
var someString = "A04.3 A new Code";
var index = someString.indexOf(" "); // Gets the first index where a space occours
var id = someString.substr(0, index); // Gets the first part
var text = someString.substr(index + 1); // Gets the text part
Run Code Online (Sandbox Code Playgroud)
您可以拆分字符串并移出返回数组中的第一个条目.然后加入剩菜,例如
var chunks = "A04.3 A new Code".split(/\s+/);
var arr = [chunks.shift(), chunks.join(' ')];
// arr[0] = "A04.3"
// arr[1] = "A new Code"
Run Code Online (Sandbox Code Playgroud)
match()您可以通过正则表达式使用和捕获您需要的内容:
"G09.4 What".match(/^(\S+)\s+(.+)/)
// => ["G09.4 What", "G09.4", "What"]
"A04.3 A new Code".match(/^(\S+)\s+(.+)/)
// => ["A04.3 A new Code", "A04.3", "A new Code"]
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,您想要的两个项目位于[1]返回[2]的数组中。
| 归档时间: |
|
| 查看次数: |
56599 次 |
| 最近记录: |