remove leading spaces from string javascript code example
Example: remove leading characters in javascript
1. Using substring()
The substring() method returns the part of the string between the specified indexes, or to the end of the string.
let str = 'Hello';
str = str.substring(1);
console.log(str);
The solution can be easily extended to remove first n characters from the string.
let str = 'Hello';
let n = 3;
str = str.substring(n);
console.log(str);
___________________________________________________________________________
2. Using slice()
The slice() method extracts the text from a string and returns a new string.
let str = 'Hello';
str = str.slice(1);
console.log(str);
This can be easily extended to remove first n characters from the string.
let str = 'Hello';
let n = 3;
str = str.slice(n);
console.log(str);
__________________________________________________________________________
3. Using substr()
The substr() method returns a portion of the string, starting at the specified index and extending for a given number of characters or till the end of the string.
let str = 'Hello';
str = str.substr(1);
console.log(str);
Note that substr() might get deprecated in future and should be avoided.