Split string and keep separators.
npm
npm install split-split
ESM:
import { split, join } from "split-split";
const [substrings, separators] = split("split split\tsplit|split", [
" ",
"\t",
"|",
]);
console.log(substrings, separators); // => ["split", "split", "split", "split"] [" ", "\t", "|"]
const str = join(substrings, separators);
console.log(str); // => "split split\tsplit|split"
CJS:
const { split, join } = require("split-split");
const [substrings, separators] = split("split split\tsplit|split", [
" ",
"\t",
"|",
]);
console.log(substrings, separators); // => ["split", "split", "split", "split"] [" ", "\t", "|"]
const str = join(substrings, separators);
console.log(str); // => "split split\tsplit|split"
CDN:
<script src="https://cdn.jsdelivr.net/npm/split-split@0.0.2"></script>
<script>
const { split, join } = splitSplit;
const [substrings, separators] = split("split split\tsplit|split", [
" ",
"\t",
"|",
]);
console.log(substrings, separators); // => ["split", "split", "split", "split"] [" ", "\t", "|"]
const str = join(substrings, separators);
console.log(str); // => "split split\tsplit|split"
</script>
The split()
method divides the given string into an ordered list of substring, puts these substrings into an array, and returns the substrings array and separators array. The division is done by searching for a pattern; where the pattern is provided as the second parameter in the method's call.
const [substrings1, separators1] = split("split split\tsplit|split", [
" ",
"\t",
"|",
]);
console.log(substrings1, separators1); // => ["split", "split", "split", "split"] [" ", "\t", "|"]
const [substrings2, separators2] = split("split split\tsplit|split", /[ \t|]/g);
console.log(substrings2, separators2); // => ["split", "split", "split", "split"] [" ", "\t", "|"]
string
(string
) — String being split.separator
(Array<string> | RegExp
) - Separator to divide the given string.
An array, the first item is an array of substrings, the second item is an array of separators.
The join()
method creates and returns a new string by concatenating all of the elements in substrings, separated by separators.
const string = join(["split", "split", "split", "split"], [" ", "\t", "|"]);
console.log(string); // => "split split\tsplit|split"
strings
(Array<string>
) — Substrings being join.separators
(Array<string>
) - Separators being join.
A string consisting of the separators inserted into the substrings.