Split string based on spaces and read that in angular2

帅比萌擦擦* 提交于 2019-12-20 19:35:14

问题


I am creating a pipe in angular2 where I want to split the string on white spaces and later on read it as an array.

let stringToSplit = "abc def ghi";
StringToSplit.split(" ");
console.log(stringToSplit[0]);

When I log this, I always get "a" as output. Where I am going wrong?


回答1:


Made a few changes:

let stringToSplit = "abc def ghi"; let x = stringToSplit.split(" "); console.log(x[0]);

The split method returns an array. Instead of using its result, you are getting the first element of the original string.




回答2:


let stringToSplit = "abc def ghi";
StringToSplit.split(" ");
console.log(stringToSplit[0]);

First, stringToSplit and StringToSplit are not the same. JS is case sensitive. Also you dont save result of StringToSplit.split(" ") anywhere and then you just output the first character of the string stringToSplit which is a. You could do like this:

    let stringToSplit = "abc def ghi";
    console.log(stringToSplit.split(" ")[0]); // stringToSplit.split(" ") returns array and then we take the first element of the array with [0]

PS. also it is more about JavaScript than TypeScript or Angular.



来源:https://stackoverflow.com/questions/44900110/split-string-based-on-spaces-and-read-that-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!