使用子字符串提取数字

时间:2012-11-13 13:30:35

标签: javascript substring substr

我有一份文件,我想从大清单中提取具体数字。

我不能在这里列出整个代码,为了简单起见,我将展示一个例子,因为代码不是必需的。

例如,假设我有一个如下所示的列表:

1: text,
2: more text,
3: etc

使用substring只能捕获字符串中的第一个字母,这将是我追求的数字。然而,当它达到10或100时会发生什么?请记住,我根本无法更改列表的格式或内容,我只能接收其中的值。

有没有办法只得到数字,没有字符串?

7 个答案:

答案 0 :(得分:3)

使用正则表达式。

类似

var matches = "121: test".match(/^(\d*):\s/)
var val;

if (matches && matches.length > 0) val = matches[1]

这个正则表达式有很多你可能需要或可能不需要的东西

^表示行的开头
()表示捕获此组 \d*表示您在一行中找到的位数 :是您示例中的冒号 \s是冒号后的单个空白字符,在您的示例中

由于我们定义了(\ d *),匹配方法将捕获匹配的那部分(数字)并使其在数组中可用。

答案 1 :(得分:2)

你可以做substring直到indexof(“:”); 示例代码:

var str="100: Hello world!";
document.write(str.substring(0, str.indexOf(":")));

你得到100分。 希望这可以帮助!祝你好运,

答案 2 :(得分:2)

您可以使用正则表达式:

var s = "1: text,\n"+
"2: more text,\n"+
"3: etc\n​​"​;

var matches = s.match( /\d+/ig);

for(var i=0;i<matches.length;++i){
   console.log(matches[i]);           
}​​​​​​​​​​

请参阅it working here

答案 3 :(得分:1)

为什么不为此使用正则表达式?

'100: asds'.replace(/^(\d+):.+$/, '$1'); // 100

答案 4 :(得分:1)

你可以获得':'的位置,然后执行string.substring(0,position)

var str="1000: this is a string";
var number = str.substring(0,str.search(':')); // 1000

答案 5 :(得分:1)

尝试

// limit split to 1 to avoid unnecessary splits
var num = "1000: rest of string".split(":", 1)[0];

我对jsPerf和结果here

上给出的方法进行了一些测试

检索所需数字的最快方法是

"1000: rest of string".substring(0, str.indexOf(":"));

如果速度很重要,那么正确的答案应该转到用户编码器。

答案 6 :(得分:0)

可能正则表达式对你来说是一个更好的选择,但是如果你需要使用上面建议的解决方案,你可以做以下几点来摆脱“{”

if(str.contains("{"))
{
     str.replace("{", "");
}