[英]Want bold text using * in html
I have a textarea, a button and a div我有一个 textarea、一个按钮和一个 div
function showres() { var text = document.getElementById('mytext'); var result = document.getElementById('resulthere'); result.innerHTML = text.value; }
<textarea name="mytxt" id="mytext"></textarea> <button onclick="showres()">Click Me</button> <div id="resulthere"></div>
It shows the value of textarea on the div on clicking the button它在单击按钮时显示 div 上 textarea 的值
I want to show bold text on div if I input a string between two * in textarea如果我在 textarea 中输入两个 * 之间的字符串,我想在 div 上显示粗体文本
For example I type Hello *Mike*
give Hello Mike in div例如,我在 div 中输入Hello *Mike*
给 Hello Mike
This can be achieved using Regex.这可以使用正则表达式来实现。
function showres() { var text = document.getElementById('mytext').value; var result = document.getElementById('resulthere'); text.match(/\\*([\\w\\s\\d]+)?\\*/g).forEach(function(match) { var str = match.substring(1, match.length - 1); text = text.replace(match, "<b>" + str + "</b>"); }); result.innerHTML = text; } document.getElementById('mytext').value = "this is *bold*"; showres();
<textarea name="mytxt" id="mytext"></textarea> <button onclick="showres()">Click Me</button> <div id="resulthere"></div>
You can use regex to match bold pattern:您可以使用正则表达式来匹配粗体模式:
var yourString = 'something left *bold text 123*';
var regex = /\*([\w\s\d]+)?\*/g;
var matches = yourString.match(regex);
// matches = ['*bold text 123*']
Then you can use replace function to replace matched patern by your way!然后你可以使用替换功能来替换匹配的模式!
for (var i = 0; i < matches.length; i++) {
yourString = yourString.replace(matches[i], yourBoldString);
}
Your can test your regex here https://regex101.com您可以在这里测试您的正则表达式https://regex101.com
You need to find the text starting and ending with **
and then slice the **
from the matching string.您需要找到以**
开头和结尾的文本,然后从匹配的字符串中切出**
。 Following is my updated code -以下是我更新的代码 -
function showres() { var text = document.getElementById('mytext'); var result = document.getElementById('resulthere'); var textVal = text.value var str = textVal.replace(/\\*([\\w\\s\\d]+)?\\*/g, function(x){ return "<b>"+x.slice(1, -1)+"</b>"; }); result.innerHTML = str; }
<textarea name="mytxt" id="mytext"></textarea> <button onclick="showres()">Click Me</button> <div id="resulthere"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.