Javascript: Search () method

Source: Internet
Author: User
ArticleDirectory
    • Syntax
    • Return Value
    • Description
    • Example 1
    • Example 2
Definition and usage

The search () method is used to retrieve the specified substring in a string or a substring that matches a regular expression.

Syntax
 
Stringobject. Search (Regexp)

Parameters Description
Regexp

This parameter can be a substring to be retrieved in stringobject or a Regexp object to be retrieved.

Note: To perform a case-insensitive search, append the flag I.

Return Value

The starting position of the first substring in stringobject that matches Regexp.

Note:If no matched substring is found,-1 is returned.

Description

The search () method does not perform global match. It ignores the flag. It also ignores the lastindex attribute of Regexp and always searches from the start of the string, which means it always returns the first matching position of stringobject.

 

Example 1

In this example, we will retrieve "w3school ":

<SCRIPT type = "text/JavaScript"> var STR = "Visit w3school! "Document. Write (Str. Search (/w3school/) </SCRIPT>

Output:

 
6

In the following example, w3school cannot be retrieved (because search () is case sensitive ).

 
<SCRIPT type = "text/JavaScript"> var STR = "Visit w3school! "Document. Write (Str. Search (/w3school/) </SCRIPT>

Output:

 
-1
Example 2

In this example, we will perform a case-insensitive search:

 
<SCRIPT type = "text/JavaScript"> var STR = "Visit w3school! "Document. Write (Str. Search (/w3school/I) </SCRIPT>

Output:

 
6

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.