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

如何在JavaScript和jQuery中为指定文本插入span标签?

Solution to Wrap Matching Text with <span> Tags

Hey there! Let's fix this up so every occurrence of the text from #txt1 gets wrapped in a <span> tag within #txt2's content. Here's how to do it properly:

Core Idea

We need to globally match every instance of the input string from #txt1 in #txt2's content, then replace each match with the wrapped version (<span>matched-text</span>). The key here is handling regular expression special characters (like ., *, ?) so the replacement works even if the input isn't just plain text like "pen".

Step-by-Step Implementation

  • Get and sanitize input values: Grab the text from #txt1 and #txt2, trimming any extra whitespace from the search term to avoid accidental empty matches.
  • Handle empty input: If #txt1 is empty, just show the original content to avoid unnecessary processing.
  • Escape regex special characters: Convert characters that have special meaning in regex into literal characters so matches are accurate (no unintended wildcard matches).
  • Global regex replacement: Use a regular expression with the g flag to replace every occurrence of the search term, not just the first one.
  • Update the result container: Insert the modified content into #rslt using innerHTML so the <span> tags render properly.

Full Working Code

Here's the complete HTML + JavaScript code that does exactly what you need:

<!-- Your existing page structure -->
<input type="text" id="txt1" placeholder="Enter search term">
<textarea id="txt2" placeholder="Enter text here">pencil penpen</textarea>
<button id="btn">Process Text</button>
<div id="rslt"></div>

<script>
document.getElementById('btn').addEventListener('click', function() {
    // Fetch all necessary elements and values
    const searchTerm = document.getElementById('txt1').value.trim();
    const originalText = document.getElementById('txt2').value;
    const resultContainer = document.getElementById('rslt');

    // Exit early if search term is empty
    if (!searchTerm) {
        resultContainer.textContent = originalText;
        return;
    }

    // Escape regex special characters to avoid syntax errors or unintended matches
    const escapedTerm = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    
    // Create a global regex and replace every matching instance
    const matchRegex = new RegExp(escapedTerm, 'g');
    const modifiedText = originalText.replace(matchRegex, '<span>$&</span>');

    // Update the result container with formatted text
    resultContainer.innerHTML = modifiedText;
});
</script>

How It Works

  • When you enter "pen" in #txt1 and click the button, the regex will find every "pen" in #txt2 — including the ones inside "pencil" and "penpen".
  • The $& in the replacement string refers to the exact text that was matched, so each "pen" gets wrapped in <span> tags correctly.
  • The regex escaping step ensures that if you enter something like "p.en", it will match the literal "p.en" instead of any character between "p" and "en".

Testing with your example:

  • Original #txt2 content: "pencil penpen"
  • Result in #rslt: "<span>pen</span>cil <span>pen</span><span>pen</span>"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:39:13