JavaScript正则需求:排除指定字符及替换未猜中字符为下划线
Got it, let's break down your two JavaScript regex questions one by one—here's practical, tested code for each scenario:
First, let's clarify the logic: I assume you mean either replace all characters NOT in your allowed set (including spaces) with underscores (keeping only your specific characters) OR replace your forbidden characters + spaces with underscores (keeping everything else). I'll cover both cases.
Case A: Keep only specific characters, replace everything else (including spaces) with underscores
If you have a variable of allowed characters (e.g., letters, numbers), we need to build a regex that matches anything outside that set. Don't forget to escape regex special characters (like [, ], ^) in your allowed list to avoid bugs:
// Example: Allowed characters are lowercase letters and numbers const allowedChars = "abcdefghijklmnopqrstuvwxyz0123456789"; // Escape regex special characters in the allowed set const escapedAllowed = allowedChars.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // Regex to match any character NOT in allowedChars (including spaces) const excludeRegex = new RegExp(`[^${escapedAllowed}]`, "g"); // Test it out const originalStr = "Hello! World 123"; const result = originalStr.replace(excludeRegex, "_"); console.log(result); // Output: "hello________123"
Case B: Replace specific forbidden characters + spaces with underscores
If instead you want to target and replace your forbidden characters (stored in a variable) plus spaces, use this approach:
// Example: Forbidden characters are symbols + space const forbiddenChars = "!@#$ "; // Escape regex special characters const escapedForbidden = forbiddenChars.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // Regex to match any forbidden character or space const replaceRegex = new RegExp(`[${escapedForbidden}]`, "g"); // Test it out const originalStr = "Hello! World 123"; const result = originalStr.replace(replaceRegex, "_"); console.log(result); // Output: "Hello_World__123"
For your Hangman-style game, we need a single regex that replaces every letter in the correct answer that isn't in the user's guessed rightString with an underscore. We'll also preserve spaces (so words stay separated) and handle case if needed.
Here's the code, with explanations:
// Your correct answer from the array const correctAnswer = this.answers[arraysIndex]; // e.g., "hangman is fun" // User's correctly guessed letters (e.g., "anf") const rightString = "anf"; // Escape any regex special characters (though rightString is usually just letters) const escapedRight = rightString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // Regex: Match any character that's NOT in rightString AND NOT a space // Add the "i" flag if you want case-insensitive matching (e.g., "A" counts as matching "a") const guessRegex = new RegExp(`[^${escapedRight}\\s]`, "gi"); // Generate the display string const displayStr = correctAnswer.replace(guessRegex, "_"); console.log(displayStr); // Output: "_a_n___ _s _u_" (for correctAnswer "hangman is fun")
Key notes:
- Remove the
iflag from the regex if you want strict case matching (e.g., user has to guess "A" instead of "a" to reveal uppercase letters). - If you don't want to preserve spaces (e.g., you want underscores for spaces too), remove
\\sfrom the regex's negated character set.
内容的提问来源于stack exchange,提问作者Mike Lamb

