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?
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?
Share Improve this question edited Nov 8, 2010 at 5:40 Yi Jiang 50.2k16 gold badges138 silver badges136 bronze badges asked Nov 8, 2010 at 5:38 LearningLearning 1,19110 gold badges20 silver badges30 bronze badges2 Answers
Reset to default 6str="testing this"; len=str.length;
document.write(str.substr(0,4));
You can use the substring
function to do this:
document.write('testing this'.substring(0, 4));