score:273

Accepted answer

instead of using the   html entity, you can use the unicode character which   refers to (u+00a0 non-breaking space):

<div>{myvalue.replace(/ /g, "\u00a0")}</div>

score:-4

so you have a value like this "hello world", and we'll say it's in this.props.value.

you can do this:

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

score:0

if you want to display a pretty 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>
)

score:0

well it's very hard to type on here without it disappearing, so i'm adding a little whitespace so everyone can see it. if you remove the whitespace from this tag < nbsp />, then you'll be able to use a non-breaking space in react.

react translates this jsx tag into a non-breaking space. weird quirk: this must also be used on the same line as the text you want to space. also, non-breaking spaces with this tag don't stack in react.

score:0

to remove space in between string, below code works for me. eg: "afee dd " result: "afeedd"

{myvalue.replace(/\s+/g, '')}

score:43

i know this is an old question, and this doesn't exactly do what you asked for, but rather than editing the string, what you want to achieve is probably be solved better using the css white-space: nowrap attribute:

in html:

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

in react:

<div style={{ whitespace: 'nowrap' }}>{myvalue}</div>

Related Query

More Query from same tag