HTML中如何利用*标记实现文本加粗?含textarea交互需求
Hey there! To achieve this, you'll need to process the text from your textarea when the button is clicked, replacing any text wrapped in asterisks with bold HTML elements. Here's a straightforward implementation:
HTML Structure
First, set up your basic elements:
<textarea id="inputText" rows="4" cols="50"></textarea> <button id="displayBtn">Display Text</button> <div id="outputDiv"></div>
JavaScript Logic
Next, add the click event listener to the button. We'll use a regular expression to find all instances of text wrapped in * and replace them with <strong> tags:
document.getElementById('displayBtn').addEventListener('click', function() { const input = document.getElementById('inputText').value; // Replace *text* with <strong>text</strong> const formattedText = input.replace(/\*(.*?)\*/g, '<strong>$1</strong>'); document.getElementById('outputDiv').innerHTML = formattedText; });
How It Works
- The regex
/\*(.*?)\*/gmatches every occurrence of text between two asterisks:\*escapes the asterisk (since it's a special character in regex)(.*?)is a non-greedy capture group that grabs the text inside the asterisks without spanning multiple asterisk pairsgflag ensures we replace all matches, not just the first one
- Setting the div's
innerHTMLto the formatted string renders the<strong>tags as bold text in the browser.
Example Result
If you type Hello *Mike*, how are *you* doing? in the textarea, the div will display:
Hello Mike, how are you doing?
This works for basic cases of asterisk-wrapped text. If you need to handle edge cases like escaped asterisks (\*), you'd adjust the regex slightly, but this covers your core requirement perfectly.
内容的提问来源于stack exchange,提问作者Yasir Mushtaq

