Common JavaScript String object indexOf () substring () split () replace ()

Source: Internet
Author: User
Tags split words


Document directory

JavaScript indexOf () method

JavaScript substring () method

JavaScript split () method

JavaScript replace () method

JavaScript indexOf () method definition and usage

The indexOf () method returns the position of the first occurrence of a specified string value.


Syntax

stringObject.indexOf(searchvalue,fromindex)

Parameters

Description


Searchvalue

Required. Specifies the string value to be retrieved.


Fromindex

Optional integer parameter. Specifies the position where the search starts in the string. The valid value is 0 to stringObject. length-1. If this parameter is omitted, It is retrieved from the first character of the string.


Description

This method retrieves the stringObject string from start to end to see if it contains the searchvalue. The start position is at the string's fromindex or the start of the string (when fromindex is not specified ). If a searchvalue is found, the first position of the searchvalue is returned. The character position in stringObject starts from 0.


Tips and comments

Note: The indexOf () method is case sensitive!


Note: If the string value to be retrieved does not appear, this method returns-1.


Instance

In this example, we will! "Different searches within the string:


<script type="text/javascript">var str="Hello world!"document.write(str.indexOf("Hello") + "<br />")document.write(str.indexOf("World") + "<br />")document.write(str.indexOf("world"))</script>

Output of the above Code:


0-16


=========================


JavaScript substring () method definition and usage

The substring () method is used to extract characters of a string between two specified subscripts.


Syntax

stringObject.substring(start,stop)

Parameters

Description


Start

Required. A non-negative integer that specifies the position of the first character of the substring to be extracted in the stringObject.


Stop


Optional. A non-negative integer is 1 more than the position of the last character of the substring to be extracted in the stringObject.


If this parameter is omitted, the returned substring ends at the end of the string.


Return Value

A new string that containsStringObjectThe content of a substring is fromStartToStop-All characters at 1. The length isStopSubtractionStart.


Description

The substring returned by the substring () method includesStartBut does not includeStop.


If the ParameterStartAndStopEquals, then this method returns an empty string (that is, a string with a length of 0 ). IfStartRatioStopThis method swaps the two parameters before extracting the substring.


Tips and comments

Important: Unlike slice () and substr (), substring () does not accept negative parameters.


Example 1

In this example, we use substring () to extract some characters from the string:


<script type="text/javascript">var str="Hello world!"document.write(str.substring(3))</script>

Output:


lo world!

Example 2

In this example, we use substring () to extract some characters from the string:


<script type="text/javascript">var str="Hello world!"document.write(str.substring(3,7))</script>

Output:


lo w


========================


JavaScript split () method definition and usage

The split () method is used to split a string into a string array.


Syntax

stringObject.split(separator,howmany)

Parameters

Description


Separator

Required. String or regular expression, which separates stringObject from the specified place.


Howmany

Optional. This parameter specifies the maximum length of the returned array. If this parameter is set, no more substrings are returned than the array specified by this parameter. If this parameter is not set, the entire string is split, regardless of its length.


Return Value

A string array. The array isSeparatorSplit the string stringObject into substrings at the specified boundary. The strings in the returned array do not includeSeparatorItself.


However, ifSeparatorIf it is a regular expression that contains a subexpression, the returned array contains strings that match these subexpressions (but does not include the text that matches the entire regular expression ).


Tips and comments

Note: If the empty string ("") is usedSeparator, Each character in the stringObject will be split.


Note: The operations executed by String. split () are the opposite to those executed by Array. join.


Example 1

In this example, we will split the string in different ways:


<script type="text/javascript">var str="How are you doing today?"document.write(str.split(" ") + "<br />")document.write(str.split("") + "<br />")document.write(str.split(" ",3))</script>

Output:


How,are,you,doing,today?H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?How,are,you

Example 2

In this example, we split strings with more complex structures:


"2: 3: 4: 5 ". split (":") // Returns ["2", "3", "4", "5"] "| a | B | c ". split ("|") // Returns ["", "a", "B", "c"]

Example 3

Use the following code to split sentences into words:


var words = sentence.split(' ')

Or use the regular expression as the separator:


var words = sentence.split(/\s+/)

Example 4

If you want to split words into letters or strings into characters, use the following code:


"Hello". split ("") // you can return ["h", "e", "l", "l", "o"]

If you only need to return a part of the characters, use the howmany parameter:


"Hello". split ("", 3) // you can return ["h", "e", "l"]


===============================


JavaScript replace () method definition and usage

The replace () method is used to replace other characters with some characters in a string, or replace a substring that matches a regular expression.


Syntax

stringObject.replace(regexp/substr,replacement)

Parameters

Description


Regexp/substr


Required. Specifies the substring or RegExp object of the pattern to be replaced.


Note that if the value is a string, it is used as the direct text mode to be retrieved, rather than being converted to a RegExp object first.


Replacement

Required. A string value. Specifies the function for replacing text or generating replacement text.


Return Value

A new string is usedReplacementIt is obtained after the first match of regexp or all matches.


Description

The replace () method of the string stringObject performs the search and replace operation. It will search for the Child string that matches regexp in stringObject, and then useReplacementTo replace these substrings. If regexp has a global flag, the replace () method replaces all matched substrings. Otherwise, it only replaces the first matched substring.


ReplacementIt can be a string or a function. If it is a string, each match will be replaced by a string. However, the $ character in replacement has a specific meaning. As shown in the following table, it indicates that the string obtained from pattern matching will be used for replacement.


Character

Replace text


$1, $2,..., $99

Text that matches the 1st to 99th subexpressions in regexp.


$ &

The substring that matches the regexp.


$'

Text on the left of the matched substring.


$'

Text on the right of the matched substring.


$

Directly count the symbols.


Note: ECMAScript v3 stipulates that the replacement parameter of the replace () method can be a function rather than a string. In this case, each match calls this function, and the string it returns will be used as the replacement text. The first parameter of this function is a matching string. The following parameter is a string that matches the subexpression in the pattern. There can be 0 or more such parameters. The following parameter is an integer that declares the position where the matching occurs in the stringObject. The last parameter is stringObject itself.


Example 1

In this example, we will replace "Microsoft" in the string with "W3School ":


<script type="text/javascript">var str="Visit Microsoft!"document.write(str.replace(/Microsoft/, "W3School"))</script>

Output:


Visit W3School!

Example 2

In this example, we will perform a global replacement. Whenever "Microsoft" is found, it will be replaced with "W3School ":


<script type="text/javascript">var str="Welcome to Microsoft! "str=str + "We are proud to announce that Microsoft has "str=str + "one of the largest Web Developers sites in the world."document.write(str.replace(/Microsoft/g, "W3School"))</script>

Output:


Welcome to W3School! We are proud to announce that W3Schoolhas one of the largest Web Developers sites in the world.

Example 3

You can use the Code provided in this example to ensure that the uppercase characters of the matching string are correct:


text = "javascript Tutorial";text.replace(/javascript/i, "JavaScript");

Example 4

In this example, we will convert "Doe, John" to "John Doe:


name = "Doe, John";name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1");

Example 5

In this example, we will replace all the quotation marks with straight quotation marks:


name = '"a", "b"';name.replace(/"([^"]*)"/g, "'$1'");

Example 6

In this example, the first letter of all words in the string is converted to uppercase:


name = 'aaa bbb ccc';uw=name.replace(/\b\w+\b/g, function(word){  return word.substring(0,1).toUpperCase()+word.substring(1);}  );

TIYReplace () 1How to Use replace () to replace characters in a string.Replace () 2-Global SearchHow to Use replace () for global replacement.Replace () 3-case insensitive searchHow to Use replace () to ensure the correctness of uppercase letters.Replace () 4How to Use replace () to convert the name format.Replace () 5How to Use replace () to convert quotation marks.Replace () 6How to Use replace () to convert the first letter of a word to uppercase.


Related Article

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.