0

I am working on a chrome extension. What i want to accomplish is, when i open a received email, the url from the email text should be detected and an alert box should show which url has been returned from the text. What I have done so far is :

function urlify(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        return url;
    })
}
var text = document.getElementsByClassName("adn ads")[0].innerText;
var html = urlify(text);

This code detects the URL but, also the returns the rest of the text with it. I just want this function to return me that specified detected url.

1
  • Could you perhaps replace document.getElementsByClassName("adn ads")[0].innerText; wit an actual example so your snippet could run? Commented Feb 11, 2018 at 18:30

2 Answers 2

1

A very simple solution I found :

function urlify(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.match(urlRegex, function(url) {
        return url;
    })
}
var text = document.getElementsByClassName("adn ads")[0].innerText;
var html = urlify(text);
console.log(html[0]);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use String#match to get a matching url. it returns an array so you can shift off the first value to get the matching value.

function urlify(text) {
  return text
    .match(/(https?:\/\/[^\s]+)/m)
    .shift()
}
var text = 'some text https://stackoverflow.com some more text'

console.log(
  urlify(text)
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.