Colonel Panic Colonel Panic - 4 months ago 10
Javascript Question

How to generate easy anagrams preserving punctuation?

I'm writing the hint system for a quiz. The hints are to be anagrams of the answers. To make the anagrams easier, I keep the first and last letters the same.

var _ = require('underscore');

var easy = function(s) {
if (s.length <= 1) {
return s;
return s[0] + _.shuffle(s.slice(1, -1)).join("") + s.slice(-1);

For multiple word answers, I want to anagram each word separately. I wrote:

var peasy = function(s) {
return s.split(/\W/).map(easy).join(" ");

However this loses any punctuation in the answer (replacing it with a space). I'd like to keep the punctuation in its original position. How can I do that?

Here are three examples to test on:

console.log(peasy("mashed potatoes"));
console.log(peasy("computer-aided design"));
console.log(peasy("sophie's choice"));

My function
above fails the second and third examples because it loses hyphen and apostrophe.


Splitting by word separator does the trick:

var peasy = function(s) {
    return s.split(/\b/).map(easy).join("");

Explanation: "computer-aided design".split(/\b/) results in ["computer", "-", "aided", " ", "design"]. Then you shuffle each element with easy and join them, getting something like "ctemopur-adeid diegsn" back...