Dynamically Wrap A Js String By Span Tags Which Can Be Dangerously Rendered In React
Solution 1:
You don't need dangerouslySetInnerHTML
for this.
Explanation:
The regex
/([a-z]+)/i
matches all substrings of 1 or more Latin alphabet letters, case insensitive.String#split
with a regex capturing group (/(...)/
) includes the captured text in the results at odd-numbered indexes. For example,'baba'.split(/(b)/)
gives you["", "b", "a", "b", "a"]
.Once you have these results, you can map the captured, odd-indexed results (
idx % 2
) tospan
elements and the even ones toReact.Fragment
s.
addAriaLabels
now returns an array of React components, which can be rendered directly inside a parent.
constaddAriaLabels = str =>
str.split(/([a-z]+)/i)
.map((substr, idx) => idx % 2
? <spankey={idx}aria-label={`column ${substr}`}>{substr}</span>
: <React.Fragmentkey={idx}>{substr}</React.Fragment>)
constParent = () => {
const str = `D = (C - B) / B`return (
<>
{addAriaLabels(str)}
</>
)
}
Solution 2:
Iterate over the string characters if the current character is an alphabet add that tags to it then assign it to already defined string else just assign the character :
const originalStr = `D = (C - B) / B`functionaddAriaLabels(str) {
let newStr = ''for (let i = 0; i < str.length; i++) {
if (str[i].match(/[A-Z]/g) && str[i].match(/[A-Z]/g).length > 0) {
newStr += `<span aria-label=\'column ${str[i]}\'>${str[i]}</span>`
} else {
newStr += str[i]
}
}
return newStr;
}
console.log(addAriaLabels(originalStr))
Post a Comment for "Dynamically Wrap A Js String By Span Tags Which Can Be Dangerously Rendered In React"