Taffrail Advice - AttributedString demo

by taffrail

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<p>

</p>

CSS

html,body {
  margin: .5rem;
}

JavaScript

// helper for AttributedString rendering
function replaceRange(s, start, end, substitute) {
  return s.substring(0, start) + substitute + s.substring(end);
}

const api ={
  data: {
    advice: [{
      "headline": "Use a Roth when single and your income is below $146,000",
      "headline_attributes": [
        {
          "range": {
            "indexStart": 48,
            "length": 8,
            "indexEnd": 56
          },
          "value": 146000,
          "valueFormatted": "$146,000",
          "type": "backlink",
          "variable": "IRS_Limit_Roth_Single_Income_Low"
        }
      ]
    }]
  }
}

const [{ 
  headline,
  headline_attributes: [{ value, valueFormatted, variable, range: { indexStart, indexEnd } }] 
}] = api.data.advice;

$("p").html( replaceRange(headline, indexStart, indexEnd, `<a href="#${variable}">${valueFormatted || value}</a>`) );