Colonel Panic Colonel Panic - 1 year ago 92
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.

Answer Source

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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download