Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  55] [ 4]  / answers: 1 / hits: 57671  / 16 Years ago, wed, march 4, 2009, 12:00:00

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!


More From » string

 Answers
3

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


Including floats:



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;}); //=> []


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

[#99893] Thursday, February 26, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lesterluiss

Total Points: 513
Total Questions: 104
Total Answers: 106

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
lesterluiss questions
Mon, Apr 4, 22, 00:00, 2 Years ago
Mon, Jul 5, 21, 00:00, 3 Years ago
Tue, May 18, 21, 00:00, 3 Years ago
Sun, Jun 21, 20, 00:00, 4 Years ago
Wed, May 20, 20, 00:00, 4 Years ago
;