DEV Community

Divyajyoti Ukirde
Divyajyoti Ukirde

Posted on • Updated on


Easy peasy split the string

The question is to split string in such a way that each element in the array has two characters and if the length of the string is odd then the missing character should get replaced by '_'.

input: "abc"
output: ["ab", "c_"]

input: "abcd"
output: ["ab", "cd"]

So the single line solution is:

const splitString2 = (str) => str.concat('_').match(/../g);
Enter fullscreen mode Exit fullscreen mode

String.prototype.match() takes parameters as regular expressions object and returns an array whose value depends on presence and absence of g flag. The g flag returns all results matching the regex.

The dot(.) in regex represents any character except newline. Therefore, /../g represents two characters to match.

Happy coding!

Top comments (0)


11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!