In JavaScript, you can make all strings in an array of strings lowercase by calling the String.prototype.toLowerCase()
method on every element of the array using Array.prototype.map()
, for example, like so:
// ES6+ const arr = ['FOO', 'Bar', 'bAz']; const newArr = arr.map((str) => str.toLowerCase()); console.log(newArr); // ['foo', 'bar', 'baz']
You can rewrite the callback to Array.prototype.map()
without arrow function to make it compatible with ES5.
The code above would create a new array with all strings in the array in lowercase. You can achieve the same with a simple for
loop as well:
const arr = ['FOO', 'Bar', 'bAz']; const newArr = []; for (let i = 0; i < arr.length; i++) { newArr.push(arr[i].toLowerCase()); } console.log(newArr); // ['foo', 'bar', 'baz']
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.