开发者

How to Count String Length & if Greater than X Length Remove X Characters - JavaScript

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?


str="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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜