Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why str.substr(0,4) is not a function?

Tags:

jquery

I'm making a script with jQuery and I got the following number 7.2387. All i have is get only 7.23, for this i've written the following code:

var str = 7.2387;
var shorter = str.substr(0,4);

But I'm getting this error:

all.js?55:92 Uncaught TypeError: str.substr is not a function
    at HTMLSpanElement.<anonymous> (all.js?55:92)
    at HTMLSpanElement.dispatch (jquery.min.js:2)
    at HTMLSpanElement.y.handle (jquery.min.js:2)

And my whole script stops working, it works only when I remove the substr(x,y) function. I made sure to have jquery updated. What's wrong?

like image 667
Ismael Quirantes Avatar asked Sep 06 '25 03:09

Ismael Quirantes


1 Answers

Because str is not a string and doesn't have a substr method. You have to convert it to a string first.

var str = 7.2387;
var shorter = String(str).substr(0, 4);
console.log(shorter);
like image 170
Federico klez Culloca Avatar answered Sep 07 '25 23:09

Federico klez Culloca