0

I achieved converting a piece of string into a component

function App() {
  const text = "Please make sure this is BUTTON";
  const modText = text.replace(/ /g, ", ");
  const parts = modText.split(",");
  const mapped = parts.map((part) => {
    return part.match(/BUTTON/) ? <button>{part}</button> : part;
  });
  return <div>{mapped}</div>;
}

but the output in the image looks really weird when I combine it back

enter image description here

I wanted it to become one sentence again something like

enter image description here

just one sentence not with " " every word

4
  • 3
    Why does it matter? The rendered output should be the same Commented Sep 26, 2022 at 13:30
  • You'll need to join() the array to get a string. Commented Sep 26, 2022 at 13:32
  • Use split to split a string to an array. Use join to merge an array to a string. Commented Sep 26, 2022 at 13:32
  • @0stone0 that will output Please make sure this is[object Object] Commented Sep 26, 2022 at 13:35

2 Answers 2

2

You can do it like this:

function App() {
  const text = "Please make sure this is BUTTON";
  const parts = text.split(/(BUTTON)/);
  const mapped = parts.map((part,i) => i&1 ? <button key={i}>{part}</button> : part || null);
  return <div>{mapped}</div>;
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

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

4 Comments

Still not really sure why it's needed
thanks @Thomas quick question though what's i&1 for?
@Skkrtskrtbroom it's a condition. Assume const text = "a BUTTON and a BUTTON and a BUTTON and a BUTTON..."; all occurances of "BUTTON" will be at odd indices in parts while the strings will be at even indices! (For this regular expression. If your regex contains more than one group, the indexing will differ!)
@Skkrtskrtbroom counter question, what's the part || null part for? why not just part? What's the difference?
0

You'll need to join() the array to get a string.

3 Comments

join() will stringify the JSX component, which is not wanted. It will output Please make sure this is[object Object]
And if you put in dangerousInnerHtml ?
This is not asked in the question.

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.