A possible solution is you can use regex to find a desired pattern and perform a split
only in this first case found pattern.
In your case, when the first -
is found, perform the split
on it, using the regex -(.*)
, that serves to make the match of the first -
.
What would your code look like:
const vogais = "a-e-i-o-u"
const arrayVogal = vogais.split(/-(.*)/, 2)
console.log(arrayVogal)
Note 2 inside split. It server to limit only 2 items, because the third is an empty string. See here
Now I’m going to create a function called splitAtTheFirstMatch
which server to perform the split
at the desired location (element
) of a given string (text
) and return me a structure similar to the one you reported ([ 'a', 'e-i-o-u' ]
) dynamically;
const vogais = 'a-e-i-o-u';
function splitAtTheFirstMatch(text, element) {
const regex = new RegExp(element + '(.*)');
return text.split(regex, 2);
}
// veja uns testes aqui
console.log(splitAtTheFirstMatch(vogais, '-'));
console.log(splitAtTheFirstMatch(vogais, 'e'));
console.log(splitAtTheFirstMatch(vogais, 'e-'));
console.log(splitAtTheFirstMatch(vogais, 'i-'));
console.log(splitAtTheFirstMatch(vogais, 'o-'));
The new RegExp
server to dynamically pass a string inside the regex.
And now you can test for any element of the string that you want to perform the split
.
OBS:
- I’m not sure this is the best regex for the case, but it works to solve your problem.
OBS2:
- With the help of @hkotsubo, an important detail about my regex and I find it interesting to add in the answer:
And .*
works because the point corresponds to any character, and the quantifier *
is "greedy" and tries to grab as many characters as possible, and so it goes to the end of the string. This is why everything that comes after the hyphen is placed in the array (without the parentheses it would not work).
Just to make the explanation more complete, the documentation of
split
says that when regex has a capture group (the parentheses), the contents of this group are also placed in the array. And.*
works because the point corresponds to any character, and the quantifier*
is "greedy" and tries to grab as many characters as possible, and so it goes to the end of the string. This is why everything that comes after the hyphen is placed in the array (without the parentheses it would not work)– hkotsubo
Exactly. Good added! I expected you to comment on my answer, because it involves regex and I do not dominate regex very well, but I have an excerpt of code that implements
...(.*)
and it was only to discover that I needed the parenthesis to break my head. I chose to use it (regex within thesplit
) to leave the answer with as little code as possible, but to answer the question.– Cmte Cardeal