1

I'm trying to determine the length of a string of characters using JavaScript & if that string of characters is greater than X length, remove enough characters to make it X length.

Here is a more specific example:

Lets say I want to count the length of this string of characters:

testing this 

I could do something like this:

str="testing this";
len=str.length;
document.write(len);

(that would return a length of 12)

Now, lets say I only want that string to be 4 characters long & I want to trim enough characters from the end of the string to only make it 4 characters long (or X characters long).

If I knew how, the result would be:

test

Anybody care to help me out?

2 Answers 2

6
str="testing this"; len=str.length;

document.write(str.substr(0,4));
1
  • Wow...I feel stupid...I can't believe it was that easy... Thank you very much for the help, I appreciate it!
    – Learning
    Nov 8, 2010 at 5:47
1

You can use the substring function to do this:

document.write('testing this'.substring(0, 4));
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.