Ottieni i primi numeri interi in una stringa con JavaScript
-
03-07-2019 - |
Domanda
Ho una stringa in un ciclo e per ogni ciclo, è piena di testi che assomigliano a questo:
"123 hello everybody 4"
"4567 stuff is fun 67"
"12368 more stuff"
Voglio solo recuperare i primi numeri fino al testo nella stringa e, ovviamente, non conosco la lunghezza.
Grazie in anticipo!
Soluzione
Se il numero è all'inizio della stringa:
("123 hello everybody 4").replace(/(^\d+)(.+$)/i,'$1'); //=> '123'
Se è da qualche parte nella stringa:
(" hello 123 everybody 4").replace( /(^.+)(\w\d+\w)(.+$)/i,'$2'); //=> '123'
E per un numero tra i caratteri:
("hello123everybody 4").replace( /(^.+\D)(\d+)(\D.+$)/i,'$2'); //=> '123'
[ addendum ]
Un'espressione regolare per abbinare tutti i numeri in una stringa:
"4567 stuff is fun4you 67".match(/^\d+|\d+\b|\d+(?=\w)/g); //=> ["4567", "4", "67"]
Puoi associare l'array risultante a un array di numeri:
"4567 stuff is fun4you 67"
.match(/^\d+|\d+\b|\d+(?=\w)/g)
.map(function (v) {return +v;}); //=> [4567, 4, 67]
Compresi i float:
"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]
Se esiste la possibilità che la stringa non contenga alcun numero, utilizzare:
( "stuff is fun"
.match(/\d+\.\d+|\d+\b|\d+(?=\w)/g) || [] )
.map(function (v) {return +v;}); //=> []
Quindi, recuperare i numeri di inizio o fine della stringa 4567 roba è 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
Altri suggerimenti
var str = "some text and 856 numbers 2";
var match = str.match(/\d+/);
document.writeln(parseInt(match[0], 10));
Se le stringhe iniziano con il numero (forse preceduto da uno spazio), è sufficiente parseInt (str, 10)
.
parseInt
salterà i primi spazi bianchi.
10
è necessario, altrimenti la stringa come 08
verrà convertita in 0
( parseInt
nella maggior parte delle implementazioni considera i numeri che iniziano con 0
come ottali).
Se vuoi un int, basta parseInt (myString, 10)
. (Il 10
indica la base 10; in caso contrario, JavaScript potrebbe provare a utilizzare una base diversa come 8 o 16.)
Usa espressioni regolari:
var re = new RegExp(/^\d+/); //starts with digit, one or more
var m = re.exec("4567 stuff is fun 67");
alert(m[0]); //4567
m = re.exec("stuff is fun 67");
alert(m); // null
Questo rimuovi
con una semplice espressione regolare ( [^ \ d]. *
):
'123 your 1st string'.replace( /[^\d].*/, '' );
// output: "123"
rimuovi tutto senza le prime cifre .