GiGa
GiGa

Reputation: 41

How transform a string with a particular identifier?

Input: 'text __city__ text __city__ text __city__'

Output: 'text <i>city</i> text <i>city</i> text <i>city</i>'

The result of the feature is passed into dangerouslySetInnerHTML.

This component is

<div dangerouslySetInnerHTML={{__html: content.replace(/(?:\r\n|\r|\n)/g, '<br />')}}></div>

for this problem (link).

My function is

const transformText = (text) => {
  const tmp = text.split('__');
  var res = '';
  var check = true;
  for (var i = 0; i < tmp.length-1; i++){
    check = !check;
    if (check) {
      res += '<i>'+tmp[i]+'</i>';
    } else if (tmp[i] != undefined){
      res += tmp[i];
    }
  }
  return res;
};

but breaks the rest of the page into IE11 browser.

Upvotes: 0

Views: 73

Answers (1)

Thomas Hennes
Thomas Hennes

Reputation: 9959

Step 1: transforming the input text.

Assuming the input is in the form "text __city__ text __city__ ... text __city__" as per your example.

const input = "text1 __paris__ text2 __london__ text3 __berlin__";
// the following will turn the input into an array of the form
// [ [text, city], [text, city], ... [text, city] ]
const pairs = input.slice(0, -2).split('__ ').map(pair => pair.split(' __'));

Step 2: using the array in a React component.

Assuming the variable pairs holds the text/city pairs as defined above, the following would be the render method inside your component (if it is class-based).

render() {
  return (
    <ul>
      {pairs.map((pair, index) => {
        return <li key={index}>{pair[0]} <i>{pair[1]}</i></li>;
      })}
    </ul>
  );
}

Upvotes: 1

Related Questions