JavaScript中用变量调用replace函数:将$替换为随机字符串的方法
Got it, let's walk through how to achieve exactly the output you're looking for. The key here is using replace() with a function that generates a new random string every time it's called—this ensures each $ gets a unique value instead of the same one repeated.
Step 1: Create a Random String Generator
First, we need a helper function to create those mixed-case alphanumeric random strings like your example. You can tweak the length or character set if you want different results:
function getRandomString(length = 5) { // Define the characters we want to include (uppercase, lowercase, numbers) const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let randomStr = ''; // Build the random string one character at a time for (let i = 0; i < length; i++) { // Pick a random index from our character set const randomIdx = Math.floor(Math.random() * charSet.length); randomStr += charSet[randomIdx]; } return randomStr; }
Step 2: Use replace() to Swap $ with Random Strings
Next, we'll use replace() with a global regex to target every $ in your original text. Instead of passing a static replacement string, we pass a function—this function runs each time a match is found, so every $ gets a unique random string wrapped in parentheses:
// Your original text (with $ as placeholders for where random strings go) const originalText = 'Som$e t$ext$e h$ere $so$me $tex$t h$ere$'; // Replace each $ with a unique (random-string) pair const modifiedText = originalText.replace(/\$/g, () => `(${getRandomString()})`); // Check the result in your console console.log(modifiedText);
How It Works
- The regex
/\$/gmatches every instance of$in the text (we escape$with a backslash because it's a special character in regular expressions). - The arrow function
() =>(${getRandomString()})`` executes for each matched$, calling our random string generator and returning it wrapped in parentheses. This guarantees every replacement is unique.
Example Output
Running this code will produce something nearly identical to your desired format:
Som(gb5t2)e t(gb95f)ext(ze6f5)e h(bs3e2)ere (avFe3)so(gEC3e)me (aFE98)tex(8FZq2)t h(dq9aA)ere(cZ3cC)
内容的提问来源于stack exchange,提问作者Msf007

