Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

Get the first integers in a string with 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.

Thanks in advance!

question from:https://stackoverflow.com/questions/609574/get-the-first-integers-in-a-string-with-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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( /(^.+)(wd+w)(.+$)/i,'$2'); //=> '123'

And for a number between characters:

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

[addendum]

A regular expression to match all numbers in a string:

"4567 stuff is fun4you 67".match(/^d+|d+|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+|d+(?=w)/g)
  .map(function (v) {return +v;}); //=> [4567, 4, 67]

Including floats:

"4567 stuff is fun4you 2.12 67"
  .match(/d+.d+|d+|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+|d+(?=w)/g) || [] )
   .map(function (v) {return +v;}); //=> []

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+|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+|d+(?=w)/g) || [] )
  .map(function (v) {return +v;}).pop(); //=> 67

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...