-3

I have string like:

"abc:12:toto:tata:titi"

and I want to got each string after ":" with a split(), so it will be "toto", "tata" and "titi" in this case.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
zh-an
  • 5
  • 3

3 Answers3

1

And I just want to got each string after :

If we use split() combined with filter() we can filter out any part that is a number.

To remove the first one, I've added a splice(1)

const input = 'abc:12:toto:tata:titi';
const res = input.split(':').slice(1).filter(n => isNaN(n) && isNaN(parseFloat(n)));

console.log(res);
[
  "toto",
  "tata",
  "titi"
]
0stone0
  • 34,288
  • 4
  • 39
  • 64
0

You can simply use String.prototype.split():

const str = 'abc:12:toto:tata:titi';

const words = str.split(':');
console.log(words);

Output:

Array(5) [ "abc", "12", "toto", "tata", "titi" ]

RegEx is not necessary, since your delimiter is constant and vary simple.

If you literally only want to get the alpha strings, immediately following a colon (":"), then use:

const str = 'abc:12:toto:tata:titi';

const filteredWords = words.slice(1).filter(word => !isNaN(parseInt(word)));
console.log(filteredWords)

Output:

Array(5) [ "toto", "tata", "titi" ]

zr0gravity7
  • 2,917
  • 1
  • 12
  • 33
  • And if I just want "toto", "tata", "titi" without "abc" and "12" How can I do it ? – zh-an Jul 09 '21 at 14:20
  • If you simply want to skip over the first two items, you can slice the `words` list: `console.log(words.slice(2))`. [`Array.prototype.slice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) will return a new array with only the items: "toto", "tata", "titi" (but will not mutate the original `words` array). – zr0gravity7 Jul 09 '21 at 14:24
0

Assuming the colon delimited values would always be either pure numbers or pure letter words:

var input = "abc:12:toto:tata:titi";
var matches = input.replace(/:\d+/g, "").split(":");
matches.shift();
console.log(matches);

The regex replacement on :\d+ removes number elements. Then we split on colon, and shift off the first element, which can't be a match as it is not preceded by a colon.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360