davedeecoder
davedeecoder

Reputation: 235

Manipulate a string and return it as html

I have a string coming in from a CMS like this:

MSRP Base Price †

The string is not mutable and I need to replace the † wrapped around superscript tags like this:

<sup>†</sup>

However, with the str.replace method, I'm using:

var superLabel = str.replace(new RegExp('†'), '<sup>†</sup>');

superLabel is returning this: MSRP Base Price < sup>†< sup>

Upvotes: 0

Views: 137

Answers (2)

Dexygen
Dexygen

Reputation: 12561

The following is one way to do what you need except for what's mentioned in the answer accounting for React, which I'm not familiar with.

var fromCMSPrefix = 'MSRP Base Price'
var fromCMS = 'MSRP Base Price †';
var superLabel = '<sup>' + fromCMS.substr(fromCMSPrefix.length).trim() + '</sup>';

Here's another:

var fromCMS = 'MSRP Base Price †';
var superLabel = '<sup>' + fromCMS.replace('MSRP Base Price', '').trim() + '</sup>';

Upvotes: 1

klugjo
klugjo

Reputation: 20885

You mentioned React in your question. React will automatically decode your string to avoid XSS attacks.

You need to use dangerouslySetInnerHTML to set your value.

Example:

// Does not work
const string = '<sup>†</sup>';
return <div>{string}</div>;

// Works
const string = '<sup>†</sup>';
return <div dangerouslySetInnerHTML={string} />;

Be careful though and make sure your input is safe.

Upvotes: 3

Related Questions