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

动态字符串处理:如何用数组不同名称替换所有Player关键词

How to Replace Each "Player" with a Different Name from an Array

Got it, let's break this down! The issue with your current single replacement is that it's swapping every "Player" with the same value—what you need is to cycle through your name array and replace each occurrence sequentially. Here are practical solutions for two common languages:

JavaScript Solution

Use the function callback in String.replace()—this lets you run custom logic every time a match is found, which we can use to pull the next name from your array.

const originalString = "Hi Player, meet Player. Player is joining us too!";
const playerNames = ["Luna", "Kai", "Zara"];
let currentIndex = 0;

const updatedString = originalString.replace(/Player/g, () => {
  // Use modulo to cycle through names if there are more Players than names
  const selectedName = playerNames[currentIndex % playerNames.length];
  currentIndex++;
  return selectedName;
});

console.log(updatedString);
// Output: Hi Luna, meet Kai. Zara is joining us too!

If you don't want to cycle names (and prefer to leave extra "Player" instances as-is once names run out), adjust the logic:

const updatedString = originalString.replace(/Player/g, () => {
  if (currentIndex < playerNames.length) {
    return playerNames[currentIndex++];
  }
  // Return the original term if no names left
  return "Player";
});

Python Solution

Python's re.sub() also supports a callback function. For a cleaner approach, use an iterator to avoid global variables:

import re

original_string = "Hi Player, meet Player. Player is joining us too!"
player_names = ["Luna", "Kai", "Zara"]
name_iterator = iter(player_names)

def replace_player_match(match):
    try:
        # Grab the next name from the iterator
        return next(name_iterator)
    except StopIteration:
        # Fallback if we run out of names
        return match.group(0)

updated_string = re.sub(r"Player", replace_player_match, original_string)
print(updated_string)
# Output: Hi Luna, meet Kai. Zara is joining us too!

Core Idea

No matter the language, the key is to handle each "Player" match individually—instead of a bulk replace, you iterate through your name array and assign the next available name to each found instance. You can tweak the fallback behavior (cycle names, leave as-is, use a default) based on your exact needs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:55:22