String substr() Method - Javascript String

Javascript examples for String:substr

Description

The substr() method returns a sub string by start and length.

To extract characters from the end, use a negative start number

The substr() method does not change the original string.

Syntax

string.substr(start, length);

Parameter Values

Parameter Description
start Required. where to start the extraction. First character is at index 0.
lengthOptional. The number of characters to extract. If omitted, it extracts the rest of the string

If start is larger than the string length-1, substr() returns an empty string.

If start is negative, it starts from the end of the string.

Return Value:

A new String, containing the extracted part of the text. If length is 0 or negative, an empty string is returned

The following code shows how to Extract parts of a string:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {// w w w  .j  a  v  a 2 s  .c o  m
    var str = "Hello world!";
    var res = str.substring(11, 12);
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

Related Tutorials