Is there a method to split a string at a specific character and include that character in the resulting array?
For instance, if we split the string "hello ??? world"
at ???
, the resulting array would be ["hello ", "???", "world"]
.
It's worth noting that the typical JavaScript split method would yield [ "hello ", " world" ]
, which does not preserve the split character in the substrings.
I have attempted to create a splitter function with some test cases, but I am unsure how to retain the split substrings with the specified character.
var splitter = (str) => {
return str.split('???');
}
//Tests
console.log(splitter("this is some text ???") === ["this is some text ", "???"])
console.log(splitter("this is ??? text???") === ["this is ", "???", " text", "???"])
console.log(splitter("this is some text") === ["this is some text"])
console.log(splitter("(???)") === ["(", "???", ")"])
console.log(splitter(" ") === [" "])
console.log(splitter(" ??? ") === [" ", "???", " "])
console.log(splitter("??????") === ["???", "???"])
console.log(splitter("?????????") === ["???", "???", "???"])
console.log(splitter("(??????") === ["(", "???", "???"])