Reputation: 15005
I need to make abbreviation
of hyphen or underscore separated words, For instance:
hyphen-separated-words
underscore_separated_words
I use the code below for hyphen-separated-words
, and it works fine.
var hyphenSeparatedWords = "hyphen-separated-words";
var abbr = hyphenSeparatedWords.match(/\b([a-z])/g).join('');
console.log(abbr) // hsw
For underscore_separated_words
, I use the code below. It works fine, but there are a lot of repetitions.
var underscoreSeparatedWords = "underscore_separated_words";
var abbr = underscoreSeparatedWords.replace(/_/g, '-').match(/\b([a-z])/g).join('');
console.log(abbr) // usw
How to make an abbreviation of underscore_separated_words
in the same way as the hyphen-separated-words
without using replace
?
How can I combine these two steps?
I have a d3 bar chart that we use internally. My font is large. And some of the xAxis labels are too long and overlaps other elements.I had two choices to fix the issue.
I opted to go for the second. Because the first one still occupies a lot of place.
Upvotes: 1
Views: 281
Reputation: 8332
An alternate solution if you'd like to work on whole sentences:
var str = 'Leave normal words and only abreviate underscore_separated_words.';
console.log(str.replace(/(?:_|(?=[a-z]*_))([a-z])[a-z]*/gi, '$1'));
Upvotes: 0
Reputation: 6501
I do not know why do not want to use replace but you can use a replace one liner, and use a replacer function:
"underscore_separated_words".replace(/[A-Z]+?(?:[_-]|\b)/gi,function(m,o,s){return m.slice(0,1)}); //usw
I think the above is way more concise and elegant
Upvotes: 1
Reputation: 30739
Why don't you try with a regex in split
that will split with either -
or _
and join
them at the end after getting the first character.
function abbr(words){
return words.split(/-|_/).map(item=>item.charAt(0)).join('');
}
var words = 'hyphen-separated-words';
var res = abbr(words);
console.log(res);
words = 'underscore_separated_words';
res = abbr(words);
console.log(res);
Upvotes: 2