'Automatically inserting hyperlinks into Google Sheets

I am trying to replace certain phrases within a cell with a hyperlinked version of that phrase. So far it will only replace the entire cell the hyperlinked version or give an error. here is the code I have tried. Really eager to hear your thoughts and thank you in advance!

function insertUrl() {
  const searchPhrase = "example text";
  const hyperlink = "google.com";
  const sheet = SpreadsheetApp.getActiveSheet()
  const range = sheet.getRange('A:Z');

while ((search = range.createTextFinder(searchPhrase, search))) {
    const searchElement = search.getElement();
    const startIndex = search.getStartOffset();
    const endIndex = search.getEndOffsetInclusive();
    searchElement.asText().setLinkUrl(startIndex, endIndex, hyperlink);
  }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source