Files
JavaScript/String/Lower.js
Fahim Faisaal 6f401c9aaf pref: optimize the algo by regex
ignore the useless traverse in best case by the help of regex and String.prototype.replace method
2022-02-17 10:30:28 +06:00

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 }