0

this might be easy but I just can´t see the forest because of trees. Given is following function:

const urlify = text => {   
    let urlRegex = /(https?:\/\/[^\s]+)(<\/td>)/g;      
    return text.replace(urlRegex, function(text) {
            return '<a href="' + text + '">' + text + '</a>';
        })
     }
      
    alert(urlify('<td>http://test.com</td>'))

more or less like the function from this SO answer.

The regex replace() function currently gets the whole match. Hence the link contains the closing </td>. How would I just access the first capture group urlRegex.exec(text)[1] inside the function?

devDan
  • 5,969
  • 3
  • 21
  • 40
Anatol
  • 1,923
  • 6
  • 26
  • 55
  • 2
    This is covered by [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter). – Kenneth K. Sep 25 '18 at 12:42

1 Answers1

1

The capture groups get passed to your function as additional arguments after the first one:

const urlify = text => {
  let urlRegex = /(https?:\/\/[^\s]+)(<\/td>)/g;
  return text.replace(urlRegex, function(_, text) 
// Ignoring the first argument ----------^^
    return '<a href="' + text + '">' + text + '</a>';
  })
}

console.log(urlify('<td>http://test.com</td>'))

But you don't need a function for this, you can use tokens in the replacement string:

const urlify = text => {
  let urlRegex = /(https?:\/\/[^\s]+)(<\/td>)/g;
  return text.replace(urlRegex, '<a href="$1">$1</a>');
}

console.log(urlify('<td>http://test.com</td>'))

More on MDN.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875