How to remove some characters from a javascript var?

3

Well I have the following code:

var tempo = "Rolling in 8.31...";

What I want is the string above, leave only the number 8, so that the var time, is as follows:

var tempo = "8";

How can I do this?

Thank you.

@EDIT:

Current Code:

setInterval(function(){ 
var tempo = document.getElementById("banner");


var match = tempo.match(/[^\d](\d+)/);
var nr = match && match[1];

console.log(nr);
}, 1000);
    
asked by anonymous 23.07.2017 / 21:07

1 answer

3

You can create a regex to search for the first number:

var tempo = "Rolling in 8.31...";
var match = tempo.match(/[^\d](\d+)/);
var nr = match && match[1];
console.log(nr); // 8 

Or cut the string with a slice:

var tempo = "Rolling in 8.31...";
var nr = parseInt(tempo.slice(11), 10);
console.log(nr); // 8

In the examples, the number is extracted. In the first as String in the second as Number . See what you prefer and if necessary convert to the correct type.

    
23.07.2017 / 21:27