Reputation: 9
I am a bit stuck on this, can't figure out how to re-insert the non-word characters ie. "-" and "!". I used regex as a way to split based on those delimiters but do need to retain the indices of the "-" and the "!" and re-introduce once I convert it back into a string from the array. The desired output is "e6t-r3s are r4y fun!" and so far I am getting: 'e6t r3s are r4y fun '
Write a function that takes a string and turns any and all "words" (see below) within that string of length 4 or greater into an abbreviation following the same rules.
abbreviate("elephant-rides are really fun!");
function abbreviate(string) {
var array = string.split(/\W/);
var newArray = [];
for (var i = 0; i < array.length; i++) {//iterates through each word
var word = array[i];
var abbrString = "";
if (word.length >= 4) {
//concat first index,count of indexes in between, last index
var innerChar = word.substring(1, word.length - 1);
var indCount = innerChar.length;
var abbrWord = word.charAt(0) + indCount + word.charAt(word.length-1);
newArray.push(abbrWord);
} else {
newArray.push(word);
}
}
return newArray.join(" ");
}
Upvotes: 1
Views: 48
Reputation: 4570
Your code can be much simpler if you will use ability to pass a function to String.replace():
function abbreviate(str) {
return str.replace(/[a-z]{4,}/ig, function (word) {
return word[0] + (word.length - 2) + word[word.length - 1];
})
}
console.log(abbreviate("elephant-rides are really fun!"));
console.log(abbreviate("Accessibility"));
Upvotes: 1