ReactJS prints a line with non-breaking spaces

I have a props that has a string that can contain characters like &. It also contains spaces. I want to replace all spaces with   .

Is there an easy way to do this? Keep in mind that I cannot just execute this syntax:

 <div dangerouslySetInnerHTML={{__html: myValue}} /> 

because first I need to replace any HTML objects with my markup. I do not want to do this, it seems too low.

Is there any way to do this?

+74
html reactjs
Jun 26 '14 at
source share
6 answers

Instead of using the &nbsp; HTML, you can just use the Unicode inextricable space:

 <div>{myValue.replace(/ /g, "\u00a0")}</div> 
+187
Jun 26 '14 at 18:21
source share

I know this is an old question, and this is not exactly what you asked, but instead of editing the line, what you want to achieve will probably be better decided to use with the CSS attribute white-space: nowrap :

In html:

 <div style="white-space: nowrap">This won't break lines</div> 

In the reaction:

 <div style={{ whiteSpace: 'nowrap' }}>{myValue}</div> 
+24
Apr 22 '16 at 22:44
source share

If you want to display nice xml:

 var str = "<test>\n\t\t<value>1</value>\n</test>\n".replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\t/g, "\u00a0").replace(/\n/g, '<br/>'); return ( <div dangerouslySetInnerHTML={{__html: str}} ></div> ) 
0
Jul 21 '17 at 22:24
source share

Well, it’s very difficult to type text here so that it doesn’t disappear, so I’m adding a little space so that everyone can see it. If you remove the space from this <nbsp /> tag, then you can use non-breaking space in React.

React translates this JSX tag into a non-breaking space. Strange quirk: this should also be used on the same line as the text you want to put in a space. In addition, non-breaking spaces with this tag do not stack in React.

0
Jun 06 '19 at 15:00
source share

To remove the space between the lines, the code below works for me. for example: "afee dd" result: "afeedd"

{myValue.replace (/ \ s + / g, '')}
0
Jun 20 '19 at 10:08
source share

So, you have a value like this "Hello world", and we will say it in this.props.value .

You can do it:

 var parts = this.props.value.split(" "), array = []; for (var i=0; i<parts.length; i++){ // add the string array.push(<span key={i * 2}>{parts[i]}</span>); // add the nbsp array.push(<span key={i * 2 + 1}>&nbsp;</span>); } // remove the trailing nbsp array.pop(); return <div>{array}</div>; 

jsbin

-four
Jun 26 '14 at 15:15
source share



All Articles