Ho una stringa in javascript come `# box2 ‘e voglio solo il’ 2 ‘da esso.
Provato:
var thestring = $(this).attr('href'); var thenum = thestring.replace( /(^.+)(\w\d+\w)(.+$)/i,'$2'); alert(thenum);
Restituisce ancora # box2 nell’avviso, come posso farlo funzionare?
Deve ospitare per qualsiasi numero di lunghezza attaccato alla fine.
Per questo esempio specifico,
var thenum = thestring.replace( /^\D+/g, ''); // replace all leading non-digits with nothing
nel caso generale:
thenum = "foo3bar5".match(/\d+/)[0] // "3"
Poiché questa risposta ha guadagnato popolarità per qualche ragione, ecco un bonus: regex generator.
function getre(str, num) { if(str === num) return 'nice try'; var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g]; for(var i = 0; i < res.length; i++) if(str.replace(res[i], '') === num) return 'num = str.replace(/' + res[i].source + '/g, "")'; return 'no idea'; }; function update() { $ = function(x) { return document.getElementById(x) }; var re = getre($('str').value, $('num').value); $('re').innerHTML = 'Numex speaks:
' + re + '
'; }
Hi, I'm Numex, the Number Extractor Oracle.
What is your string?
What number do you want to extract?
Dovresti provare quanto segue:
var txt = "#div-name-1234-characteristic:561613213213"; var numb = txt.match(/\d/g); numb = numb.join(""); alert (numb);
risultato
1234561613213213
Usando la funzione di corrispondenza.
var thenum = thestring.match(/\d+$/)[0]; alert(thenum);
jsfiddle
Penso che questa espressione regolare servirà al tuo scopo:
var num = txt.replace(/[^0-9]/g,'');
Dove txt
è la tua stringa.
In pratica elimina tutto ciò che non è una cifra.
Penso che puoi ottenere lo stesso risultato usando anche questo:
var num = txt.replace(/\D/g,'');
Prova quanto segue: string.replace(/[^0-9]/g, '');
Questo cancellerà tutti i caratteri non numerici, lasciando solo le cifre nella stringa
function retnum(str) { var num = str.replace(/[^0-9]/g, ''); return parseInt(num,10); }
console.log('abca12bc45qw'.replace(/[^0-9]/g, '')); console.log('#box2'.replace(/[^0-9]/g, ''));
Ho provato tutte le combinazioni citate sopra con questo codice e l’ho fatto funzionare, è stato l’unico a lavorare su quella stringa -> (12) 3456-7890
var str="(12) 3456-7890"; str.replace( /\D+/g, '');
Risultato: "1234567890"
Obs: so che una stringa del genere non sarà sull’attr, ma qualunque sia, la soluzione è migliore, perché è più completa.
E questo è uno snippet che estrae i prezzi con valuta e formattazione:
var price = "£1,739.12"; parseFloat(price.replace( /[^\d\.]*/g, '')); // 1739.12
puoi usare un ottimo metodo parseInt
convertirà le cifre iniziali in un numero
parseInt("-10px"); // will give you -10
Per una stringa come #box2
, questo dovrebbe funzionare:
var thenum = thestring.replace(/^.*(\d+).*$/i,'$1');
jsFiddle:
Con le espressioni regolari , come ottenere numeri da una stringa, ad esempio:
String myString = "my 2 first gifts were made by my 4 brothers"; myString = myString .replaceAll("\\D+",""); System.out.println("myString : " + myString);
il risultato di myString
è ” 24
”
puoi vedere un esempio di questo codice in esecuzione qui: http://ideone.com/iOCf5G
Puoi usare l’espressione regolare.
var txt="some text 2"; var numb = txt.match(/\d/g); alert (numb);
Ciò avviserà 2.
È ansible utilizzare la libreria di stringhe Underscore come segue
var common="#box" var href="#box1" _(href).strRight(common)
il risultato sarà: 1
Vedi: https://github.com/epeli/underscore.string
DEMO:
http://jsfiddle.net/abdennour/Vyqtt/
Codice HTML:
Codice JS:
var comm="#box" $('a').click(function(){ $('div').html(_($(this).attr('href')).strRight(comm))})
se hai suffisso come segue:
href="box1az"
Puoi usare la prossima demo:
http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all,prefix,suffix){ var left=_(all).strRight(prefix); return _(left).strLeft(suffix); }
Ecco un solt. che controlla per nessun dato
var someStr = 'abc'; // add 123 to string to see inverse var thenum = someStr.match(/\d+/); if (thenum != null ) { console.log(thenum[0]); } else { console.log('no number'); }
Usa questo codice a una riga per ottenere il primo numero in una stringa senza ottenere errori:
var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);
si prega di controllare sotto javaScript, lì è ansible ottenere solo il numero
var txt = "abc1234char5678#!9"; var str = txt.match(/\d+/g, "")+''; var s = str.split(',').join(''); alert(Number(s));