mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-12-19 06:58:15 +08:00
ignore the useless traverse in best case by the help of regex and String.prototype.replace method
25 lines
584 B
JavaScript
25 lines
584 B
JavaScript
/**
|
|
* @function lower
|
|
* @description Will convert the entire string to lowercase letters.
|
|
* @param {String} str - The input string
|
|
* @returns {String} Lowercase string
|
|
* @example lower("HELLO") => hello
|
|
* @example lower("He_llo") => he_llo
|
|
*/
|
|
|
|
const lower = (str) => {
|
|
if (typeof str !== 'string') {
|
|
throw new TypeError('Invalid Input Type')
|
|
}
|
|
|
|
const lowerString = str.replace(/[A-Z]/g, (_, indexOfUpperChar) => {
|
|
const asciiCode = str.charCodeAt(indexOfUpperChar);
|
|
|
|
return String.fromCharCode(asciiCode + 32);
|
|
})
|
|
|
|
return lowerString;
|
|
}
|
|
|
|
export { lower }
|