JavaScript string processing functions using summary _javascript Tips

Source: Internet
Author: User
1. Calculate the length of a string
Copy Code code as follows:

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

2.indexOf () method

How to use IndexOf () to position the first occurrence of a specified character in a string.
Copy Code code as follows:

<script type= "Text/javascript" >
var str= "Hello world!"//w lowercase
document.write (Str.indexof ("H") + "<br/>")//0
document.write (Str.indexof ("World") + "<br/>")//-1
document.write (Str.indexof ("World"))//6
</script>

3.match () method

Finds a specific character in a string, and returns this character if it is found.
Copy Code code as follows:

<script type= "Text/javascript" >
var str= "Hello world!"
document.write (Str.match ("World") + "<br/>")//world
document.write (Str.match ("World") + "<br/>")//null
document.write (Str.match ("worlld") + "<br/>")//null
document.write (Str.match ("world!"))//world!
</script>

4. How to replace characters in a string-replace ()
Replace some characters in a string with the Replace () method.
Copy Code code as follows:

<script type= "Text/javascript" >
var str= "Visit cnblogs.com!"
document.write (Str.replace (/cnblogs.com/, "mamogu.com"))
</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.