Is it possible, without using external libraries, to parse a string with hashtag then style it with the Text
component?
const string = "Let's #Tweet on #Twitter";
// Expect:
// Let's <Text style={{ color: 'blue' }}>#Tweet</Text> on <Text style={{ color: 'blue' }}>#Twitter</Text>
I thought this would do:
import React from 'react';
import { Text } from 'react-native';
export const HASHTAG_FORMATTER = string => {
return string.replace(/(^|\s)(#[a-z\d-]+)/ig, `$1${<Text style={{ color: 'blue' }}>$2</Text>}`);
}
Usage:
import React from 'react';
import { View, Text } from 'react-native';
import { HASHTAG_FORMATTER } from '../../utilities/hashtag';
const Home = props => {
return (
<View>
<Text>{HASHTAG_FORMATTER("Let's #Tweet on #Twitter")}</Text>
<View>
)
}
What I got instead was:
Let's [object Object] on [object Object]
See example: https://codesandbox.io/s/react-native-69dwm?fontsize=14
Is there a way to achieve this in jsx? Thanks.
You can't use back references like this, you can use callback function of replace when you want to have a dynamic evaluation
const HASHTAG_FORMATTER = string => {
return string.replace(/(^|\s)(#[a-z\d-]+)/ig, (m, g1, g2) => {
return g1 + "<span style={color:'green'}>" + g2 + "< /span>"
});
}
console.log(HASHTAG_FORMATTER("#tweet"))
To solve your specific problem you need to solve it by splitting string and then building Text components as per the values
Demo
const HASHTAG_FORMATTER = string => {
return string.split(/((?:^|\s)(?:#[a-z\d-]+))/gi).filter(Boolean).map((v,i)=>{
if(v.includes('#')){
return <Text key={i} style={{color:'green'}}>{v}</Text>
} else{
return <Text key={i}>{v}</Text>
}
})
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With