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">
<h1></h1>

CSS

html,body {
  margin: .5rem;
}

JavaScript

// helper for AttributedString rendering
function replaceRange(s, attributes) {
  attributes.reverse().forEach(attr => {
    const {
      value,
      valueFormatted,
      variable,
      range: {
        indexStart: start,
        indexEnd: end
      }
    } = attr;
    
    const substitute = `<a href="#${variable}">${valueFormatted || value}</a>`;
    s = s.substring(0, start) + substitute + s.substring(end);
  });
  
  return s;
}

const api = {
  data: {
    advice: [{
      "headline": "Use a Roth when single and your income is below $146,000",
      "headline_attributes": [{
          "range": {
            "indexStart": 16,
            "length": 6,
            "indexEnd": 22
          },
          "value": "single",
          "type": "backlink",
          "variable": "Tax_Filing_Status"
        },
        {
          "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: attributes
}] = api.data.advice;

$("h1").html(replaceRange(headline, attributes));