Last active
December 28, 2021 10:48
-
-
Save rauschma/9990f427cbc9d1ac591e3502c1ef63a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@WebReflection Good point. Others did this on Twitter, too. I changed it.