最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 6
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)

  1. 暂无评论