How to remove some characters from a var javascript?

Asked

Viewed 91 times

3

Well I have the following code:

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

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

var tempo = "8";

How can I do that?

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);
  • You always have the same text Rolling in ? or the text may vary? you can give more examples?

  • The text, is always the same, the only thing that can vary is 8.31, I wanted everything to disappear and only to be 8. It can be for example 10.20, 15.23 etc... That is, I intend to remove the decimals and the remaining characters. And leave only the main number

1 answer

3


You can create a regex to find 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 bead:

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 right type.

  • This is giving me the time error.match is not a Function

  • @Gonçalo What gives you console.log(typeof tempo, tempo)?

  • Not defined, I will update the question with my current code. I am trying the code on this site: www.csgopolygon.com on the console.

  • @Gonçalo I can’t load this link, but if you have an element you must use the innerHTML or textContent to have the content. For example: var tempo = document.getElementById("banner").textContent;

  • 1

    Perfect, Thanks again Sergio!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.