Javascript Intercept string Several functional usage detailed

Source: Internet
Author: User

There are many ways to intercept a string (excluding the split () method that intercepts a number of groups based on incoming parameters) here is a substring, so do not say the split () method.

Slice (), substr (), substring () altogether three methods, each of which is different, they can pass one or two parameters, the first parameter is the starting position, slice () and substring () The second parameter is the ending position (the output to the previous character at the end position), and the substr is the character length, but the case is different when the negative numbers are passed in.

Here are some examples of negative numbers:

The code is as follows Copy Code

var stringvalue = "Hello World";
Console.log (Stringvalue.slice (-3));
Console.log (Stringvalue.substring (-3));
Console.log (Stringvalue.substr (-3));
Console.log (Stringvalue.slice (3,-4));
Console.log (Stringvalue.substring (-4, 3));
Console.log (Stringvalue.substring (3,-4));
Console.log (STRINGVALUE.SUBSTR (3,-4));

Output:

Rld
Hello World
Rld
Lo W
Hel
Hel

The last one is an empty string, and the substring bar is converted to 0, which seems to mean from 0 to another parameter. Slice () The mean minus sign is the reverse number.

Add: Using regular expressions
Method 2

The code is as follows Copy Code

<script>
Alert ("ABCDEFG". Match (/.*) (. { 2})/) [1])
</script>

<script>
Alert ("ABCDEFG". Match (/.{ 2}$/))
</script>

And like IndexOf, you can.

The following example illustrates the use of the IndexOf method.

  code is as follows copy code

function Indexdemo (str2) {
var str1 = ' Babebibobubabebibobu '
var s = str1.indexof (STR2);
return (s);
}

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.