Split string based on spaces and read that in angular2
Asked Answered
N

3

19

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?

Naughton answered 4/7, 2017 at 7:54 Comment(2)
I hope you understand why you always got "a" by now.Hurwit
it is not assigning value to same string. And if also it will do, it will be like assigning string[] in stringThoer
G
48

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.

Gylys answered 4/7, 2017 at 7:59 Comment(4)
Wonderful. Glad to help.Gylys
Feel free to mark the answer as completed if it solved your problem. It will help others as well.Gylys
Thanks @RaduCojocariSink
Thank @Radu Cojocari, split() function return an arrayMitman
D
5
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.

Dictograph answered 4/7, 2017 at 8:1 Comment(1)
This is a much clearer answer. At least you explained what went wrong.Hurwit
W
0

i created this npm package for it: https://www.npmjs.com/package/search-string-eerg

    function customSearch(s, p) {
      let x = p.split(" ");
        var find = true;
        for (var partIndex in x) {
    if (s.toLowerCase().indexOf(x[partIndex]) > -1) {
      // Let this item feature in the result set only if other parts of the
      // query have been found too
      find = find && true;
    } else {
      // Even if a single part of the query was not found, this item
      // should not feature in the results
      find = false;
    }
     }
     return find;
}
Working answered 15/3, 2021 at 15:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.