Sometimes, we want to split a string once in our JavaScript code.
In this article, we’ll look at how to split a string once in our JavaScript code.
Split a String Once in JavaScript
To split a string once in our JavaScript code, we can use the JavaScript string’s indexOf
method with the JavaScript string’s slice
method to find the index of the first instance of the separator and then do the slicing.
For instance, we can write:
const s = "1|Ceci n'est pas une pipe: | Oui";
const i = s.indexOf('|');
const splits = [s.slice(0, i), s.slice(i + 1)];
console.log(splits)
We have the s
string that we want to split by the first |
.
Then we call indexOf
with '|'
to get the index of the first instance of the |
symbol.
Next, we call slice
with 0 and i
to get the substring before the first |
.
And likewise, we call slice
with i + 1
to get the part after the first |
.
We then put both substrings into the splits
array.
Therefore, splits
is:
["1", "Ceci n'est pas une pipe: | Oui"]
Conclusion
To split a string once in our JavaScript code, we can use the JavaScript string’s indexOf
method with the JavaScript string’s slice
method to find the index of the first instance of the separator and then do the slicing.