如何在JavaScript和jQuery中为指定文本插入span标签?
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
#txt1and#txt2, trimming any extra whitespace from the search term to avoid accidental empty matches. - Handle empty input: If
#txt1is 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
gflag to replace every occurrence of the search term, not just the first one. - Update the result container: Insert the modified content into
#rsltusinginnerHTMLso 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
#txt1and 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
#txt2content:"pencil penpen" - Result in
#rslt:"<span>pen</span>cil <span>pen</span><span>pen</span>"
内容的提问来源于stack exchange,提问作者FeYa
相关产品推荐
相关产品推荐

