[JavaScript] String startswith, endswith and contains Implementation
When we do programming with strings, it's very common to have the following questions:
- how do I check whether the string starts with prefix?
- how do I check whether the string ends with suffix?
- how do I check whether the string contains sub-string?
We will show how to do these case by case in JavaScript:
String startswith
We can use JavaScript built-in indexOf() function to check whether a string starts (or begins) with prefix. For alternative solution, please refer to reference [1].
/**
* The string starts with prefix?
* @param {string} string The string starts with prefix?
* @param {string} prefix The string starts with prefix?
* @return {boolean} true if string starts with prefix, otherwise false
*/
startswith = function(string, prefix) {
return string.indexOf(prefix) == 0;
};
String endswith
Again we use JavaScript built-in indexOf() function to check whether a string ends with suffix. For alternative solution, please refer to reference [2].
/**
* The string ends with suffix?
* @param {string} string The string ends with suffix?
* @param {string} suffix The string ends with suffix?
* @return {boolean} true if string ends with suffix, otherwise false
*/
endswith = function(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) != -1;
};
String contains
The same trick of JavaScript built-in indexOf() function to check whether a string contains another string. For alternative solution, please refer to reference [3].
/**
* The string contains substr?
* @param {string} string The string contains substr?
* @param {string} substr The string contains substr?
* @return {boolean} true if string contains substr, otherwise false
*/
contains = function(string, substr) {
return string.indexOf(substr) != -1;
};
References:
[1] | How to check if a string “StartsWith” another string? |
[2] | endsWith in javascript |
[3] | How can I check if one string contains another substring? |
[4] | JavaScript String indexOf() Method |
[5] | JavaScript basename() |