Ad

How To Substring 0 To 30, But Only If There Is Over 30 Characters

- 1 answer

I have a little problem, I want to substring a String, to max 30 characters, but when I do string.substring(0, 30), it works fine if the string is 30+ characters, but if not, it comes with an error.

Does anyone know how to fix that?

Ad

Answer

You should be getting "RangeError: Value not in range: 30" error.

Try to add a length control before that.

if (string.length < 30)

  return string;

else

  return string.substring(0, 30);

Let's shorten the code above:

String resultText = (string.length < 30) ? string : string.substring(0, 30);
Ad
source: stackoverflow.com
Ad