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

如何用正则表达式替换不同字符并添加条件?解决字符串转换异常

Fixing Slug Generation with Regex: Removing Extra Hyphens

Got it, let's break down how to solve this problem and get the clean slug you need. First, let's look at why your original regex isn't working:

What's Wrong with the Original Regex?

Your current pattern .replace(/\s+|'|()/g, '-') has a few critical issues:

  • The () in regex is a capturing group, not a literal parenthesis—so it doesn't actually match the parentheses in your string.
  • It replaces each individual match (like a single space, a single apostrophe, or even the zero-width positions matched by ()) with a hyphen, leading to multiple consecutive hyphens when there are adjacent special characters (like the existing - next to spaces).
  • It doesn't handle converting the string to lowercase, which is required for your desired output.

Solution: Step-by-Step Clean Slug Generation

We'll build a regex workflow that handles all edge cases and produces the clean slug you want. Here are two solid approaches:

Approach 1: Target Specific Characters (Exact Match)

Use this if you only want to replace the specific characters in your example (apostrophes, parentheses, spaces, hyphens):

const original = "George's - super duper (Computer)";
const cleanSlug = original
  .toLowerCase() // Convert all characters to lowercase first
  .replace(/['()\s-]+/g, '-') // Match 1+ of the target chars, replace with ONE hyphen
  .replace(/^-|-$/g, ''); // Remove hyphens from start/end if they exist

console.log(cleanSlug); // Output: "georges-super-duper-computer"
  • ['()\s-]+: The + ensures any sequence of the target characters gets replaced with a single hyphen, eliminating extra hyphens. We escape ( and ) with backslashes to match them as literal characters.
  • ^-|-$: This removes any leading or trailing hyphens that might result if the string starts/ends with a special character.

Approach 2: General-Purpose Slug (Handle All Non-Alphanumeric Chars)

If you want a more robust solution that works for any special characters (not just the ones in your example), use this:

const original = "George's - super duper (Computer)";
const cleanSlug = original
  .toLowerCase()
  .replace(/[^a-z0-9]/g, '-') // Replace ANY non-alphanumeric char with a hyphen
  .replace(/-+/g, '-') // Merge consecutive hyphens into one
  .replace(/^-|-$/g, ''); // Trim leading/trailing hyphens

console.log(cleanSlug); // Output: "georges-super-duper-computer"
  • [^a-z0-9]: The ^ inside the character class means "not"—so this matches anything that isn't a lowercase letter or number.
  • /-+/g: Merges any number of consecutive hyphens into a single one, which fixes the extra hyphen problem.

How This Works for Your Example

Let's walk through the first approach with your original string:

  1. George's - super duper (Computer) → george's - super duper (computer) (after toLowerCase())
  2. Replace sequences of apostrophes, spaces, hyphens, and parentheses with single hyphens → georges-super-duper-computer-
  3. Remove the trailing hyphen → georges-super-duper-computer

Perfect, that's exactly the output you need!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:28:18