How to use substring in React Native?

Asked

Viewed 1,601 times

1

How to use substring in React Native?

if (total >= 1000){
      const total2 = total.substr(total.lenght - 3, total.lenght);
      total = total2 + '.' + total.substr(total.lenght - (total.lenght - 1), total.lenght - 3);
    }

Error:

Undefined is not a Function (evaluating 'total.substr(total.lenght - 3, total.lenght);')

My intention is to check if the value is greater than or equal to 1000, divide the string into two parts and put the point in the third house backwards: 1,000

  • 1

    total.toString().substr(total.lenght - 3, total.lenght); as you can see, it’s converting to string for the method substr is for string. String.prototype.substr()

  • I’m starting with React Native, but as far as I know, it uses javascript and it has no variable typing. My intention really is to take the total number and treat it as string. Tomorrow I will try to convert to see if it resolves

1 answer

3


There is a syntax error in your code: the correct is length and not lenght (the h in the end).

Besides doing it wrong in the substr. The error in question is because the variable total is not a string. The substr will only work with strings.

Convert the variable first total string with .toString() and then apply the substr to achieve the desired result:

total = 2000;
if (total >= 1000){
   const total_string = total.toString();
   const total2 = total_string.substr(0, total_string.length - 3);
   total = total2 + '.' + total_string.substr(total_string.length - 3, total_string.length);
   alert(total);
}

  • 1

    I didn’t even realize I was wrong length.

Browser other questions tagged

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