Javascript 用于将字符串中的单词大写的管道出错
我正在尝试在我的Angular应用程序中创建一个更健壮的大写管道。起初,我使用的大写管道只需要大写单个单词。现在我遇到了一个可以有多个单词的情况。这就是我的管道现在处理这种情况的样子:Javascript 用于将字符串中的单词大写的管道出错,javascript,angular,typescript,pipe,angular-pipe,Javascript,Angular,Typescript,Pipe,Angular Pipe,我正在尝试在我的Angular应用程序中创建一个更健壮的大写管道。起初,我使用的大写管道只需要大写单个单词。现在我遇到了一个可以有多个单词的情况。这就是我的管道现在处理这种情况的样子: transform(input: any) { if (input !== null) { const stringArr = input.split(' '); let result = ' '; const cap = stringArr.lengt
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;
}
}
转换(输入:任意){
如果(输入!==null){
const stringArr=input.split(“”);
让结果=“”;
const cap=stringArr.length;
for(设x=0;x
但我在控制台中发现了这个错误:
原始异常:input.split不是一个函数
有什么想法吗?String#split
函数只能在字符串上使用,否则您将收到一个原始异常:input.split不是函数
错误
您必须设置一个条件,即给定元素必须是字符串
,如果不是,则必须将其更改为字符串
,或者忽略它
if (input !== null && typeof input == 'string') {
input.split(' ')
} else {
input.join().split(' ')
}
if(!input!=null)
这里有一个双负数,因此只有当input
为null
时,split才会运行。作为旁注,我建议使用Array.prototype.join()
重新组合整个字符串,这样可以避免内部if
及其代码重复input.split(“”).map(word->word.substring(0,1).toUpperCase()+word.substring(1)).join(“”)应该可以很好地工作。if(input!==null&&typeof input==string'){
试试。if(input!==null&&typeof input==string'){input.split(“”)或者{input.join().split(“”)可以很好地工作。谢谢@Kind user!