JavaScript substr() method


JavaScript substr() Method

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>

<p id="demo">点击按钮截取字符串。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
    var str="Hello world!";
    var n=str.substr(2,3);
    document.getElementById("demo").innerHTML=n;
}
</script>

</body>
</html>

Run instance»

Click the "Run Example" button to view the online example


Definition and usage

The substr() method can be extracted from the string starting from The specified number of characters starting from the subscript.

Tips: The parameters of substr() specify the starting position and length of the substring, so it can be used instead of substring() and slice().
In IE 4, the value of parameter start is invalid. In this BUG, ​​start specifies the position of the 0th character. In later versions, this BUG has been corrected.
ECMAscript does not standardize this method and therefore discourages its use.

Note: The substr() method does not change the source string.


Browser support

QQ截图20161108165429.png

All major browsers support the substr() method


Syntax

string.substr(start,length)

Parameter value

ParametersDescription
startRequired. The starting index of the substring to be extracted. Must be a numeric value. If negative, this parameter declares the position from the end of the string. That is, -1 refers to the last character in the string, -2 refers to the second to last character, and so on.
length Optional. The number of characters in the substring. Must be a numeric value. If this parameter is omitted, the string from the beginning to the end of stringObject is returned.

Return value

TypeDescription
StringA new string containing the extracted part of the text

Technical details

# #JavaScript Version: 1.0

##More examples

Examples

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>

<p id="demo">点击按钮截取字符串</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
	var str="Hello world!";
	var n=str.substr(2);
	document.getElementById("demo").innerHTML=n;
}
</script>

</body>
</html>

Run Instance»
Click the "Run Instance" button to view the online instance