JS string length function Detailed introduction

Source: Internet
Author: User

We just use

The code is as follows Copy Code

var str = "465464656464566";
var strlength = str.length;

Example 1

The code is as follows Copy Code

<script type= "Text/javascript" >
var vtext= "I like Www.111cn.net"
document.write ("<p>" + Vtext + "</p>")
document.write (Vtext.length)
</script>

<p>javascript example code explains: First declare a variable vtext, assign "I like Www.111cn.net" to Vtext, and then use

Document.Write it out, and then use the Length property to compute the vtext and display it, Vtext contains 16 words.

Character, the space is also counted, the final result is 16. If you write in Chinese, you will get the length of the medium character. Like you wrote, "I like cloth.

"I'll get the length of this string, it's 8."
</p>

Example 2

The code is as follows Copy Code

<body>

<script type= "Text/javascript" >

var txt= "Hello world!"
document.write (Txt.length)

</script>

</body>

Lose 12

Using the above experience we write a string intercept function

The code is as follows Copy Code

<div id= ' jsdiv ' style= "border:1px solid #ccc" ></div>
<script type= "Text/javascript" >
Gets the true length of the string (two bytes converted to two single-byte)
function Getstractuallen (schars)
{
Return Schars.replace (/[^x00-xff]/g, "xx"). Length;
}

Intercept fixed-length substring ssource for string Ilen length
function Getinterceptedstr (ssource, Ilen)
{
if (Ssource.replace (/[^x00-xff]/g, "xx"). Length <= Ilen)
{
return ssource;
}

var str = "";
var L = 0;
var Schar;
for (var i=0; Schar=ssource.charat (i); i++)
{
str = Schar;
L + = (Schar.match (/[^x00-xff]/)!= null? 2:1);
if (l >= ilen)
{
Break
}
}

return str;
}
var str1= "It is a function of a string intercept, this is a test!";
Alert (Getstractuallen (STR1));
Alert (GETINTERCEPTEDSTR (str1,25));
</script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.