Using the JavaScript substr() String method you can get the portion of the string, starting at the specified index and extending for a given number of characters afterward.
substr(start)
substr(start, length)
This method returns a part of a string and does not change the original string. To extract characters from the end of the string, use a negative start position.
Note: An empty string is returned if the length is 0 or negative.
JavaScript substr()
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
let text = "Hello world!";
let res = text.substr(1, 4);
console.log(res);
console.log(text.substr(2));
//Only the first
console.log(text.substr(0, 1));
//Only the last:
console.log(text.substr(-1, 1));
</script>
</body>
</html>
Output:
More examples
const aString = 'Mozilla';
console.log(aString.substr(0, 1)); // 'M'
console.log(aString.substr(1, 0)); // ''
console.log(aString.substr(-1, 1)); // 'a'
console.log(aString.substr(1, -1)); // ''
console.log(aString.substr(-3)); // 'lla'
console.log(aString.substr(1)); // 'ozilla'
console.log(aString.substr(-20, 2)); // 'Mo'
console.log(aString.substr(20, 2)); // ''
Using substring()
as an Alternative
let str = "Hello, World!";
let result = str.substring(7, 12);
console.log(result); // Output: "World"
Using slice()
as an Alternative
let str = "Hello, World!";
let result = str.slice(7, 12);
console.log(result); // Output: "World"
Both substring()
and slice()
methods are more commonly used and recommended for modern JavaScript development.
Comment if you have any doubts or suggestions on this JS string method tutorial.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version