Fre*_*red 32 javascript string string-formatting
我在循环中有一个字符串,对于每个循环,它都填充了如下所示的文本:
"123 hello everybody 4"
"4567 stuff is fun 67"
"12368 more stuff"
Run Code Online (Sandbox Code Playgroud)
我只想检索字符串中文本的第一个数字,当然,我不知道长度.
提前致谢!
Koo*_*Inc 57
如果数字位于字符串的开头:
("123 hello everybody 4").replace(/(^\d+)(.+$)/i,'$1'); //=> '123'
Run Code Online (Sandbox Code Playgroud)
如果它在字符串中的某个位置:
(" hello 123 everybody 4").replace( /(^.+)(\w\d+\w)(.+$)/i,'$2'); //=> '123'
Run Code Online (Sandbox Code Playgroud)
对于字符之间的数字:
("hello123everybody 4").replace( /(^.+\D)(\d+)(\D.+$)/i,'$2'); //=> '123'
Run Code Online (Sandbox Code Playgroud)
[ 附录 ]
用于匹配字符串中所有数字的正则表达式:
"4567 stuff is fun4you 67".match(/^\d+|\d+\b|\d+(?=\w)/g); //=> ["4567", "4", "67"]
Run Code Online (Sandbox Code Playgroud)
您可以将结果数组映射到Numbers数组:
"4567 stuff is fun4you 67"
.match(/^\d+|\d+\b|\d+(?=\w)/g)
.map(function (v) {return +v;}); //=> [4567, 4, 67]
Run Code Online (Sandbox Code Playgroud)
包括花车:
"4567 stuff is fun4you 2.12 67"
.match(/\d+\.\d+|\d+\b|\d+(?=\w)/g)
.map(function (v) {return +v;}); //=> [4567, 4, 2.12, 67]
Run Code Online (Sandbox Code Playgroud)
如果存在字符串不包含任何数字的可能性,请使用:
( "stuff is fun"
.match(/\d+\.\d+|\d+\b|\d+(?=\w)/g) || [] )
.map(function (v) {return +v;}); //=> []
Run Code Online (Sandbox Code Playgroud)
因此,要检索字符串的开头或结尾编号 4567 stuff is fun4you 2.12 67"
// start number
var startingNumber = ( "4567 stuff is fun4you 2.12 67"
.match(/\d+\.\d+|\d+\b|\d+(?=\w)/g) || [] )
.map(function (v) {return +v;}).shift(); //=> 4567
// end number
var endingNumber = ( "4567 stuff is fun4you 2.12 67"
.match(/\d+\.\d+|\d+\b|\d+(?=\w)/g) || [] )
.map(function (v) {return +v;}).pop(); //=> 67
Run Code Online (Sandbox Code Playgroud)
Eug*_*zov 46
var str = "some text and 856 numbers 2";
var match = str.match(/\d+/);
document.writeln(parseInt(match[0], 10));
Run Code Online (Sandbox Code Playgroud)
如果字符串以数字开头(可能前面有空格),那么简单parseInt(str, 10)就足够了.
parseInt将跳过前导空格.
10是必要的,因为否则字符串08将被转换为0(parseInt在大多数实现中,考虑0以八进制开头的数字).
这个replace方法用一个简单的正则表达式([^\d].*):
'123 your 1st string'.replace( /[^\d].*/, '' );
// output: "123"
Run Code Online (Sandbox Code Playgroud)
删除所有没有第一个数字的内容。
| 归档时间: |
|
| 查看次数: |
35428 次 |
| 最近记录: |