How to remove hyphens of a text on a <Text> tag on React Native?

Viewed 1670

I had started recently to study react native and I'm passing through a several problem on my application. I have a tag that I need to pass a text, that's ok. But I can't let this text had hyphens on it, because it's focus on children. So, I need to remove any hyphen that is generated automatically for the tag. Anybody here has passed from some situation like that?

<Text 
style={mixedGuideTextStyle}
font="madeWaffle">
"testetdgtsd sdfugkgfus wsefjkhksdhfsdh sjfkdhgdschsdk swedifuhskdichksh sdhcksdhjchds"
</Text>
3 Answers

If I understand correctly, you want the text content of the <Text> element to be dynamically rendered so that any '-' character is removed.

A simple solution would be to render the text content of <Text> inside of an expression (ie via { }), and use the .replace() method on the string to replace all '-' characters with an empty string like so:

<Text 
style={mixedGuideTextStyle}
font="madeWaffle">
{ "testetdgtsd-sdfugkgfus-wsefjkhksdhfsdh".replace(/-/gi, '') }
</Text>

This will cause the text element to render with this string content:

testetdgtsd-sdfugkgfus-wsefjkhksdhfsdh

You need to include the global flag:

var str="185-51-671";
var newStr = str.replace(/-/g, "");

You could aslo

str.split('-').join('');

this should also work.

You're good to go!

You can create your own component that does that for you applying the replace function pointed by @Akshay Mulgavkar

function NoHyphensText({ children }) {
  return (
          <Text 
            style={mixedGuideTextStyle}
            font="madeWaffle">
              {children.replace(/-/gi, ' ')}
          </Text>
  );
}

And then just use it like this

<NoHyphensText>Render-this-whithout-hyphens</NoHyphensText>
Related