如何检查字符串是否包含特定独立字符?避免子串误匹配
Got it, I totally get what you're after here. You don't just want to know if the string has a "1" somewhere—you want to check for a standalone, single "1" that isn't part of a longer sequence like "11" or stuck inside another number like "213". The basic includes("1") check is way too broad for this, so let's fix it.
Solution 1: Use a Regular Expression for Precise Matching
Regex is perfect here because it lets you define exactly what counts as a "standalone" 1. Here's a function that does exactly what you need:
function hasStandaloneOne(str) { // Matches: // - The string is exactly "1" // - "1" is at the start followed by a non-digit // - "1" is between two non-digits // - "1" is at the end preceded by a non-digit return /(^|\D)1(\D|$)|^1$/.test(str); }
Let's test this against your examples:
hasStandaloneOne("1")→true(correct)hasStandaloneOne("11")→false(correct, since it's two 1s together)hasStandaloneOne("213")→false(correct, the 1 is part of a longer number)hasStandaloneOne("a 1 b")→true(works for standalone 1s in text)hasStandaloneOne("1,2")→true(works for 1s separated by non-digits)
Breakdown of the regex:
(^|\D): Matches either the start of the string, or a non-digit character1: The exact character we're looking for(\D|$): Matches either a non-digit character, or the end of the string|^1$: Handles the edge case where the entire string is just "1"
Solution 2: Iterate Through the String (No Regex Needed)
If regex feels intimidating, you can loop through each character and check manually. This is more verbose but super straightforward:
function hasStandaloneOne(str) { // Handle the simple case first if (str === "1") return true; for (let i = 0; i < str.length; i++) { if (str[i] === "1") { const prevChar = i > 0 ? str[i-1] : null; const nextChar = i < str.length - 1 ? str[i+1] : null; // Make sure the 1 isn't surrounded by another 1 if ((prevChar !== "1") && (nextChar !== "1")) { return true; } } } return false; }
This function checks every "1" in the string to ensure it doesn't have another "1" right before or after it. It also handles the case where the string is just "1" upfront.
Either of these approaches will solve your problem—pick whichever one makes more sense for your codebase and comfort level!
内容的提问来源于stack exchange,提问作者Vine

