1

How do I make this string text

first video link: https://www.youtube.com/watch?v=123456

second video link: https://www.youtube.com/watch?v=8123123`;

become

first video link: 
<a href="https://www.youtube.com/watch?v=123456">
  https://www.youtube.com/watch?v=123456
</a>

second video link: 
<a href="https://www.youtube.com/watch?v=8123123">
  https://www.youtube.com/watch?v=8123123
</a>

I have written a regular expression to parse the link

Here is what I have.

<script type="text/javascript">
var myString =`first video link: https://www.youtube.com/watch?v=123456
second video link: https://www.youtube.com/watch?v=8123123`; 
var myRegexp = /(https|http)?:\/\/[\S]+/g;
var match = myRegexp.exec(myString);
console.log(match[0]) // https://www.youtube.com/watch?v=123456
</script>
rj487
  • 4,476
  • 6
  • 47
  • 88

2 Answers2

0

Use the following solution:

var myString = "first video link: https://www.youtube.com/watch?v=123456\nsecond video link: https://www.youtube.com/watch?v=8123123"; 
var myRegexp = /https?:\/\/\S+/g;
var match = myString.replace(myRegexp, '<a href="$&"><br>  $&<br></a>');
document.body.innerHTML = match;

The https?:\/\/\S+ will match http, then an optional s, then ://, and then \S+ will match one or more non-whitespace symbols. The whole match value can be inserted into the resulting string within a String#replace() replacement pattern via a $& backreference.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

See retrieve all matches for a regular expression for details on how to access all matches of myRegexp. Your sample code looks like string processing, your problem might be addressed correctly by working on elements of a source html-document or by processing a string and contribute the result into a document.

document.createElement('a').href=match[0];

Hint: Your regex (/(https|http)?://[\S]+/g) does match "://not.an.url" as well. either just mark the 's' of "https" an optional, or include "://" to the optional protocol part of your expression.

Community
  • 1
  • 1