如果我有一个字符串包含
abc: def - 01:00, ghi - 02:00
这个字符串的任何部分都可以改变,除了字符串中分隔符的顺序,即 :
, -
, :
, 、
、-
和 :
如何获取第一个 :
之前的文本并将其粘贴到变量中供以后使用?
另外,我如何获取第一个 -
和 之间的文本,
并将其粘贴到不同的变量中?
最佳答案
How do I get the text before the first
:
and stick it into a variable for later use?
var text = 'abc: def - 01:00, ghi - 02:00',
firstChunk = text.substring(0, text.indexOf(':'));
// firstChunk is "abc"
And also, how do I get the text between the first
-
and,
and stick that into a different variable?
var secondChunk = text.substring(text.indexOf('-') + 1, text.indexOf(','));
// secondChunk is " 01:00"
字符串函数引用:
- >
String.indexOf
- >
String.substring
- 要去除多余的空格(如
"01:00"
),请使用String.trim
关于javascript - 使用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6344467/