Reputation: 6289
I am trying to create a more robust capitalize pipe in my Angular app. Initially the capitalize pipe I had was only needed to capitalize single words. Now I have a situation where there can be multiple words. This is what my pipe now looks like to handle this kind of scenario:
transform(input: any) {
if (input !== null) {
const stringArr = input.split(' ');
let result = ' ';
const cap = stringArr.length;
for (let x = 0; x < cap; x++) {
stringArr[x].toLowerCase();
if (x === cap - 1) {
result += stringArr[x].substring(0, 1).toUpperCase() + stringArr[x].substring(1);
} else {
result += stringArr[x].substring(0, 1).toUpperCase() + stringArr[x].substring(1) + ' ';
}
}
return result;
}
}
But I am getting this error in the console:
ORIGINAL EXCEPTION: input.split is not a function
Any ideas as to what's off here?
Upvotes: 1
Views: 100
Reputation: 41893
String#split
function is usable only on strings, else you will receive an ORIGINAL EXCEPTION: input.split is not a function
error.
You have to set a condition, that the given element must be a string
, if not - it has to be changed (if it's possible) into a string
or just ignored.
if (input !== null && typeof input == 'string') {
input.split(' ')
} else {
input.join().split(' ')
}
Upvotes: 1