Reputation: 137622
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 peasy
above fails the second and third examples because it loses hyphen and apostrophe.
Upvotes: 1
Views: 173
Reputation: 89565
It's more simple to use String.prototype.replace
instead of splitting:
easy
function.var _ = require('underscore');
var peasy = function(s) {
return s.replace(/\B\w{2,}\B/g, function (m) {
return _.shuffle(m).join('');
});
}
Upvotes: 2
Reputation: 10968
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...
Upvotes: 3