Javascript Reference - JavaScript String substring() Method








The substring() method gets the sub-string from a string, between two specified indices.

The returned string is between start and end, not including character at ending index.

If start is greater than end, this method will swap the two arguments. str.substring(5,1) becomes str.substring(1,5).

If either start or stop is less than 0, this method converts the value to 0.

The substring() method does not change the original string, only the sub string is returned.

Browser Support

substring() Yes Yes Yes Yes Yes




Syntax

stringObject.substring(start, end);

Parameter Values

Parameter Description
start Required. Where to start. First character is at index 0
end Optional. Where to end. The returned string doesn't include the ending character. It stops at end-1. If omitted, it uses the string length

Return Value

A new String containing the extracted characters.

Example

Extract characters from a string:


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--  w w w  .  j  a  v a2 s .  c  o  m-->
    var str = "Hello world!";
    var res = str.substring(1, 4);
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2:missing the end


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--   w  w  w.  j  a va 2  s.c  om-->
    var str = "Hello world!";
    var res = str.substring(2);
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 3:start is greater than end


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from  w  ww. ja v  a  2 s .com-->
    var str = "Hello world!";
    var res = str.substring(4, 1);
    document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 4: negative start

If start is less than 0, substring() method converts uses 0 instead.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from ww w .ja v  a2s  . c o  m-->
    var str = "Hello world!";
    var res = str.substring(-3);
    document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>

The code above is rendered as follows: