在两个分隔符之间将字符串加粗,使用JavaScript JSX。

huangapple go评论66阅读模式
英文:

Make string bold in paragraph between two delimiters javascript JSX

问题

现在,在JSX/JavaScript中,我想要使两个下划线之间的字符串变为粗体(这是来自数据库的字符串要变为粗体格式)

英文:

From DB, we are getting string in following format.

_This is string from DB_. Make sure this is format from DB

Now, on JSX/javascript, I want to make string between two underscores as bold (This is string from DB to be bold format)

答案1

得分: 1

您可以使用正则表达式来匹配两个下划线之间的字符串,并用<b>标签包裹它。您可以使用字符串对象的replace方法来执行此操作。例如,您可以修改您的代码如下:

const dbString = "_这是来自数据库的字符串_。确保这是来自数据库的格式。";
const formattedString = dbString.replace(/_(.*?)_/g, "<b>$1</b>");
return <div dangerouslySetInnerHTML={{ __html: formattedString }} />;
英文:

You can use a regular expression to match the string between two underscores, and wrap it with a <b> tag. You can use the replace method of the string object to perform this operation. For example, you can modify your code like this:

const dbString = &quot;_This is string from DB_. Make sure this is format from DB&quot;;
const formattedString = dbString.replace(/_(.*?)_/g, &quot;&lt;b&gt;$1&lt;/b&gt;&quot;);
return &lt;div dangerouslySetInnerHTML={{ __html: formattedString }} /&gt;;

huangapple
  • 本文由 发表于 2023年7月10日 19:27:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定