javascripttypescriptindexof

Add to string at specific index at for each occurence


I am trying to add to a string, in this instance I am wanting to alter the href and add a string to the beginning of each href in a string. I have figured out how to do it for one instance, but not if the string has more than one occurrence. Is there a best practice to accomplish this?

This is what I have to add to if there is just one occurrence (it also works with multiple, but will only alter the first occurrence).

  let stringOne = '<div>
    <p>A cool label</p>
    <a href="123idofanitem">Link 1</a>
    <p>A cool label</p>
    <span>
      <a href="1234idofanitem">Link 2</a>
    </span>
    <ul>
      <li>
        <a href="12345idofanitem">Link 3</a>
      </li>
      <li>
        <a href="123456idofanitem">Link 4</a>
      </li>
    </ul>
  </div>'

  let index = stringOne.indexOf('href="');
  let output = [stringOne.slice(0, index + 6),
     'https://www.google.com/',
      stringOne.slice(index + 6),].join('');//added +6 to account for href="

I am trying to replace all href with https://www.google.com/{existingHREF}

A final note would be that stringOne could have infinite amount of links in it, so that's why I am trying to work my way to a solution where I could loop or something of the sort through all of them and replace them.


Solution

  • You can use RegExp with a .replace function:

    stringOne.replace(/href="/g, 'href="https://www.google.com/')

    The g means 'global', is a flag that match every ocurrences in the string