使用JavaScript获取字符串中的第一个整数 [英] Get the first integers in a string with JavaScript

查看:295
本文介绍了使用JavaScript获取字符串中的第一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在循环中有一个字符串,对于每个循环,它都填充了如下所示的文本:

I have a string in a loop and for every loop, it is filled with texts the looks like this:

"123 hello everybody 4"
"4567 stuff is fun 67"
"12368 more stuff"

我只想检索字符串中文本的第一个数字,当然,我不知道长度。

I only want to retrieve the first numbers up to the text in the string and I, of course, do not know the length.

提前致谢!

推荐答案

如果数字位于字符串的开头:

If the number is at the start of the string:

("123 hello everybody 4").replace(/(^\d+)(.+$)/i,'$1'); //=> '123'

如果它在字符串中的某个位置:

If it's somewhere in the string:

(" hello 123 everybody 4").replace( /(^.+)(\w\d+\w)(.+$)/i,'$2'); //=> '123'

以及字符之间的数字:

("hello123everybody 4").replace( /(^.+\D)(\d+)(\D.+$)/i,'$2'); //=> '123'

[附录]

匹配字符串中所有数字的正则表达式:

A regular expression to match all numbers in a string:

"4567 stuff is fun4you 67".match(/^\d+|\d+\b|\d+(?=\w)/g); //=> ["4567", "4", "67"]

您可以将生成的数组映射到数字数组:

You can map the resulting array to an array of Numbers:

"4567 stuff is fun4you 67"
  .match(/^\d+|\d+\b|\d+(?=\w)/g)
  .map(function (v) {return +v;}); //=> [4567, 4, 67]

包括花车:

"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]

如果存在字符串不包含任何内容的可能性数字,使用:

If the possibility exists that the string doesn't contain any number, use:

( "stuff is fun"
   .match(/\d+\.\d+|\d+\b|\d+(?=\w)/g) || [] )
   .map(function (v) {return +v;}); //=> []

因此,检索字符串的起始或结束编号 4567东西是fun4you 2.12 67

So, to retrieve the start or end numbers of the string 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

这篇关于使用JavaScript获取字符串中的第一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆