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

如何用JavaScript替换语句中的多个单词?附场景与代码示例

故事文本动态替换功能实现方案

需求

  • 将故事语句中所有character(含首字母大写的Character)替换为输入框填写的角色名称
  • 若下拉列表选择女性性别,将故事内的he/his/him(含首字母大写形式)对应替换为she/her/Her;选择男性则保留原代词

修改后的代码

HTML代码(可选优化版)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Story Customizer</title>
</head>
<body>
  <div class="test-container">
    <h1>Story</h1>
    <form> 
      <label>Character's Name:</label>
      <input class="name-input-field" type="text">
      <br><br>
      <label for="sex">Character's sex?</label>  
      <select name="sex" id="maleFemale">
          <option disabled hidden selected>Select</option>
          <option value="male">Male</option>
          <option value="female">Female</option>
      </select>  
      <br><br>
      <button type="button" class="submit">Submit</button>
    </form>
  </div>
  <h3 class="statement"></h3>
  <p class="statement"></p>
  <script src="test3.js"></script>
</body>
</html>

优化说明:合并两个表单为一个,给按钮添加type="button"避免默认提交刷新页面。

JavaScript代码

var nameInput = document.querySelector(".name-input-field");
var maleFemale = document.querySelector("#maleFemale");
var statements = document.querySelectorAll(".statement");
var submitButton = document.querySelector(".submit");

submitButton.addEventListener("click", () => {
    // 获取角色名,为空时用默认值
    const characterName = nameInput.value.trim() || "Character";
    const selectedGender = maleFemale.value;

    // 原始故事文本
    let storyText = `Character woke up and he immediately got dressed. His clothes were hanging on the chair and so he put them on. His friend asked him if he was going to work; character told his friend that he was.`;

    // 替换所有character(不区分大小写,保留原格式)
    storyText = storyText.replace(/character/gi, match => {
        return match.charAt(0) === match.charAt(0).toUpperCase()
            ? characterName.charAt(0).toUpperCase() + characterName.slice(1)
            : characterName.toLowerCase();
    });

    // 女性性别时替换代词
    if (selectedGender === "female") {
        storyText = storyText
            .replace(/\bhe\b/gi, match => match === "He" ? "She" : "she")
            .replace(/\bhis\b/gi, match => match === "His" ? "Her" : "her")
            .replace(/\bhim\b/gi, match => match === "Him" ? "Her" : "her");
    }

    // 更新所有故事展示元素
    statements.forEach(el => el.innerText = storyText);
});

关键逻辑说明

  1. 全局替换字符:使用/character/gi正则表达式,g实现全局替换,i忽略大小写,同时根据原匹配文本的大小写调整替换后名字的格式,保证文本一致性。
  2. 精准替换代词:用\b匹配单词边界,避免误替换包含目标字母的其他单词;根据原代词的大小写返回对应女性代词,比如His替换为Her,his替换为her。
  3. 空输入处理:给角色名设置默认值,防止用户未输入时出现空白内容。
  4. 批量更新元素:用querySelectorAll获取所有故事展示元素,确保所有区域同步更新文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:15:19