Skip to content Skip to sidebar Skip to footer

Dynamically Wrap A Js String By Span Tags Which Can Be Dangerously Rendered In React

I have a string and I would like to add span tags to the alphabets alone with an aria-label tag. The end result will be dangerously rendered in React. Please advice. This is what I

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) to span elements and the even ones to React.Fragments.

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"