120

I have some props that has a string that could contain characters such as &. It also contains spaces. I want to replace all spaces with  .

Is there an easy way I can do this? Bear in mind that I cannot just render using this syntax:

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

because I would first have to replace any HTML entities with their markup. I don't want to have to do this, it seems too low level.

Is there a way I can do this?

4
  • 1
    why is this related to react? Commented Jun 26, 2014 at 14:03
  • 1
    It's not entirely clear what you want to do. Do you want to just replace all spaces with &nbspl;, do you want to display HTML tags literally or is there something else you want to do? Commented Jun 26, 2014 at 14:03
  • It depends on when myValue is accessible. You could wait for it in appropriate lifecycle function, parse it and set a parsed flag that prevents multiple parsing. Commented Jun 26, 2014 at 14:46
  • if you want to render &nbsp; unescaped to the dom with react, you're going to need to use the dangerouslySetInnerHTML method. I don't really see a way around that since you could use javascript to create a string replacing spaces with &nbsp; but without using the dangerouslySetInnerHTML method these will be escaped by react. Commented Jun 26, 2014 at 19:42

7 Answers 7

312

Instead of using the &nbsp; HTML entity, you can use the Unicode character which &nbsp; refers to (U+00A0 NON-BREAKING SPACE):

<div>{myValue.replace(/ /g, "\u00A0")}</div>
Sign up to request clarification or add additional context in comments.

7 Comments

Please take note that the unicode character you're using above is being blacklisted by browsers because of its abuse by phishing schemes. See kb.mozillazine.org/Network.IDN.blacklist_chars
@BenAlpert Good point. Yes. Very good point. Just IDN addresses to my knowledge.
simple yet effective. thx @BenAplert after even after 3yrs of post.
This worked for me when nothing else did. Thanks for the help!
That blacklist applies to domain names, not HTML code.
|
52

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>

3 Comments

Thank you! This is the better answer. And in my case (a bunch of links I don't want wrapping, but I also don't want on one line), I added a::after { content:' '; white-space:normal}
I don't think this works if you want to keep some words together (i.e. names) and others to wrap. With <p style={{word-wrap: nowrap}}>Edgar Woolf, Noel Langley, Florence Ryerson</p>, nothing wraps and the string overflows the container. In this case, dangerouslySetInnerHTML appears to be the only option for selectively applying &nbsp; between specific words.
For one, you need to use whiteSpace:nowrap not word-wrap:nowrap. Second, a safer approach is to either use a span for the words you want to not wrap, or as one of the other answers suggested you can replace only &nbsp; with the unicode equivalent (rather than allowing arbitrary html in your string which is a big security risk).
5

In my opinion, the best way to display &nbsp; is to print it explicitly in the code. (It is sad that react does not support such simple, basic, features out of the box.) If react's jsx throws error, it means nbsp was put incorrectly into code.

Simple rule is that all special characters should be wrapped with tag.

In most cases it's just possible to put it as it is:

return <span>{n}&nbsp;followers</span>;

But, if you want to add something like that:

// this will cause an error
{number > 0 && (<strong>{number}</strong>&nbsp;)}

you need to wrap part with nbsp with parent tag (for example, with empty):

{number > 0 && (
  <>
    <strong>{number}</strong>
    &nbsp;
  </>
)}

This might be useful in cases when special character is need only in some cases (when number is greater than 0, for example).

Comments

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>
)

Comments

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.

1 Comment

Doesn't work: Warning: The tag <nbsp> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter
0

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

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

Comments

-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

Comments

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.