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

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 /\*(.*?)\*/g matches 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 pairs
    • g flag ensures we replace all matches, not just the first one
  • Setting the div's innerHTML to 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:13:20