You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript正则生成连字符/下划线分隔单词的缩写?

Unified Regex for Hyphen & Underscore Separated Word Abbreviations

Got it, let's fix this so you can generate abbreviations for both hyphen-separated and underscore-separated words with a single, clean regex—no more duplicate code!

The Problem with Your Current Approach

Your hyphen-separated solution works because \b (word boundary) correctly picks out the start of each word after a hyphen. But underscores count as "word characters" in regex, so \b won't trigger between an underscore and the next letter. That’s why your underscore code ended up feeling repetitive (I’m guessing you were splitting on _ and mapping over the array, right?).

The Unified Solution

We can build a regex that matches either the start of the string, or a hyphen/underscore, then captures the first letter that follows. Here's a clean implementation:

// Test strings
const hyphenWords = "hyphen-separated-words";
const underscoreWords = "underscore_separated_words";

// Regex to capture initial letters after start, hyphen, or underscore
const abbreviationRegex = /(?:^|[-_])([a-z])/g;

// Helper function to generate abbreviation
function getAbbreviation(str) {
  // Grab all matching groups
  const matches = str.match(abbreviationRegex);
  // Extract the captured letter from each match and join them
  return matches ? matches.map(match => match.slice(-1)).join('') : '';
}

// Test it out!
console.log(getAbbreviation(hyphenWords)); // Output: hsw
console.log(getAbbreviation(underscoreWords)); // Output: usw

How This Regex Works

Let’s break down /(?:^|[-_])([a-z])/g:

  • (?:^|[-_]): A non-capturing group that matches either:
    • ^: The start of the string (to capture the first word’s initial)
    • [-_]: A hyphen or underscore
  • ([a-z]): Captures the lowercase letter immediately after the start of the string or a separator
  • g: Global flag to find all matches in the string

Even Shorter One-Liner Version

If you prefer a more concise approach without a helper function, use replace to strip out everything except the captured initials:

const hyphenAbbr = hyphenWords.replace(/(?:^|[-_])([a-z])|./g, (_, capture) => capture || '');
const underscoreAbbr = underscoreWords.replace(/(?:^|[-_])([a-z])|./g, (_, capture) => capture || '');

console.log(hyphenAbbr); // hsw
console.log(underscoreAbbr); // usw

This regex replaces every character with either the captured initial (if it matches our target pattern) or an empty string—leaving exactly the abbreviation we want.

内容的提问来源于stack exchange,提问作者mahan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:44:32