0

I'm using Regex to bold characters using a double underscore. This is my regex, which works:

"I'm making __this__ bold".replace(/\__([^*]+)\__/g,"<b>$1</b>");

Which gives me this:

"I'm making <b>this</b> bold" 

But how do I get it work with React? I have the following code, which doesn't work:

 {cars.map(car => {
   return (
    <div>
     <p>{car.description.replace(/\__([^*]+)\__/g,"<b>$1</b>")}</p>
    </div>         
  )})}

In this case {car.description} would be for example:

   "The __Audi RS 6 quattro__, commonly referred to as __the RS6__"

And I would like it to show up as:

"The Audi RS 6 quattro, commonly referred to as the RS6"

EDIT:

With this

  <p>{car.description.replace(/\__([^*]+)\__/g,"<b>$1</b>")}</p>

I get back a string:

   "The <b>Audi RS 6 quattro</b>, ..."

But how do I make JSX recognise to show it as bold, and not with the
tags on the frontend?

2
  • Please try this, <p>{car.description.replace(/\__([^*]+)\__/g,"<b>$1</b>")}</p> Commented Aug 26, 2017 at 8:15
  • why and how Commented Aug 26, 2017 at 8:22

2 Answers 2

3

What you need is dangerouslySetInnerHTML

{cars.map(car => {
   var description = car.description.replace(/\__([^*]+)\__/g,"<b>$1</b>");
   return (
    <div>
     <p dangerouslySetInnerHTML={{__html: description}}/>
    </div>         
  )})}

Sample snippet

const App = () => {
   var car = "I'm making __this__ bold";
   var newCar = car.replace(/\__([^*]+)\__/g,"<b>$1</b>");
   return (
       <div dangerouslySetInnerHTML={{__html: newCar}} />
   )
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

What if description contains characters such as & or <?
0

I advise against using dangerouslySetInnerHTML, which — as implied by its name — is dangerous (the output won’t be what you expect if car.description contains characters such as & or <).

You can produce your own elements instead:

return (
  <p>{car.description.split('__').map((v, i) => i % 2 ? <b key={i}>{v}</b> : v)}</p>
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.