Sometimes, we want to return a substring from a string to the end using JavaScript.
In this article, we’ll look at how to return a substring from a string to the end using JavaScript.
How to return a substring from a string to the end using JavaScript?
To return a substring from a string to the end using JavaScript, we can use some string methods.
For instance, we write:
const strIn = 'http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe';
const searchTerm = '/dashboard.php?';
const searchIndex = strIn.indexOf(searchTerm);
const strOut = strIn.substr(searchIndex + searchTerm.length);
console.log(strOut)
to get substring from strIn after '/dashboard.php?'.
To do this, we get the index of the first character of searchTerm with strIn.indexOf(searchTerm).
Then we call strIn.substr with searchIndex + searchTerm.length to return a substring from strIn starting from index searchIndex + searchTerm.length + 1 to the end of the string.
Therefore, strOut is 'page_id=projeto_lista&lista_tipo=equipe '.
Conclusion
To return a substring from a string to the end using JavaScript, we can use some string methods.