1

I am using the code below to extract the URL from a string variable named description. It works but it will merge duplicated URLs.

let geturl = new RegExp(/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/igm);

let urlExtracted = description.match(geturl);

Is there any method to change the code so that I could extract all the URLs in the order the URLs are being found in the variable even though they are duplicated?

1
  • 4
    Can you provide a list of examples and expected output? Commented Nov 5, 2018 at 0:05

1 Answer 1

1

Create a tokenized match object from the string and the pattern, then convert that token object into a list.

Just realized that answer I suggested uses the same code as your question. But I tried out the code you're using in this code pen and couldn't replicate the error with this example:

var y = "https://www.youtube.com/watch?v=tIM-kdmKhnE  https://codepen.io/hellopravin/pen/NqLgqB  hi https://stackoverflow.com/questions/8441915/tokenizing-strings-using-regular-expression-in-javascript  https://www.youtube.com/watch?v=tIM-kdmKhnE";
var regex = /(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/igm;

var match = y.match(regex);
//document.write(Array.from(match));
document.write(match);
Sign up to request clarification or add additional context in comments.

5 Comments

You shuld show some code to make your answer better
Thanks, what is the output from your code? The URL of www.youtube.com.... only show up once right? I wanted the URLs to show up as many times as the URL is found in the text
i have just checked, seems like my string has some issues instead of the regular expression in the code. Let me check and confirm
I would like to comment that there is no issue with the codes, it is the input string issues. Thanks for the feedback and help.
No problem, If you wouldn't mind accepting my answer with the check next to my answer I'd appreciate it. @Calvin

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.