Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active December 28, 2021 10:48
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rauschma/9990f427cbc9d1ac591e3502c1ef63a6 to your computer and use it in GitHub Desktop.
Save rauschma/9990f427cbc9d1ac591e3502c1ef63a6 to your computer and use it in GitHub Desktop.
function hyphenize(str) {
// /y is to make sure that there are no characters between the matches
// /g is so that .match() works the way we need here
// /u is not strictly necessary here, but generally a good habit
return str.match(/([a-z]{1,2})/uyg).join('-');
}
assert.equal(
hyphenize('hello'), 'he-ll-o'
);
assert.equal(
hyphenize('abcdefghijkl'), 'ab-cd-ef-gh-ij-kl'
);
// A simple `for` loop works quite well, too
function hyphenize2(str) {
let result = '';
for (let index = 0; index < str.length; index += 2) {
if (index > 0) {
result += '-';
}
// .slice() doesn’t mind if the second argument is too large
result += str.slice(index, index+2);
}
return result;
}
@BaggersIO
Copy link

I really like this solution. Thank you!

@WebReflection
Copy link

I'd go with:

/([a-z]{1,2})/uyg

@rauschma
Copy link
Author

@WebReflection Good point. Others did this on Twitter, too. I changed it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment