mahan
mahan

Reputation: 15005

How to make abbreviation of underscore or hyphen separated words using regex in JavaScript?

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?

Update

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.

  1. Wrap labels like this in bl.ocks.org
  2. Make an abbreviation of them. When you hover on a bar or its label, display the complete name.

I opted to go for the second. Because the first one still occupies a lot of place.

Upvotes: 1

Views: 281

Answers (3)

SamWhan
SamWhan

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'));

Here at regex101.

Upvotes: 0

ibrahim tanyalcin
ibrahim tanyalcin

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

Ankit Agarwal
Ankit Agarwal

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

Related Questions