0

Youtube description characters are quiet expensive so we are trying to find a way to replace all youtube link entries in e textarea for the shorter ones.

Youtube's short url is "http://youtu.be/"+ [video id].

The file I'm loading contains all types of youtube links and the outcome of this script should be to shorten all youtube links found in the file.

Here is an example of the file:

Best Commercials Ever
    10. T-Mobile Super Bowl 2016 Commercial: 
    https://www.youtube.com/watch?v=OUVFxBd8OCI&ab_channel=EpicExperiment 
    9. Butterfinger Super Bowl Commercial 2016:
    https://www.youtube.com/watch?v=mXLWAAn7gEk

My script should look up this video and return:

Best Commercials Ever 
    10. T-Mobile Super Bowl 2016 Commercial: youtu.be/OUVFxBd8OCI
    9. Butterfinger Super Bowl Commercial 2016: youtu.be/mXLWAAn7gEk

With this regex I am able to find pretty much any youtube link and transform it to the shorten one by extracting the video id:

var videoid = url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/);

if(videoid != null) {
 return "http://youtu.be/" + videoid[1];
} else { 
 console.log("The youtube url is not valid.");
}

However this function will only work with a simple string and not with a multiline one (txt file). Now I need something that would run this function inside the text file and replace all matches...

Thanks in advance for your help!

1 Answers1

0

If you read it from a textarea you could split it into lines by '\n' character like described here How to read line by line of a text area and then use your code for each of the lines.

However if you need to work in javascript with actual file, you could use HTML5 File API (example tutorial is here https://www.html5rocks.com/en/tutorials/file/dndfiles/)

Community
  • 1
  • 1
Pati K
  • 129
  • 2
  • 11
  • Thanks for replying! I couldn't solve it yet. I am able to split and replace each link but can't find a way to join the (multiline) variable and send it back to the textarea exactly as it was before but just with the youtube links corrected. Any light is appreciated, cheers! – user3817728 Oct 08 '16 at 14:11
  • Did you try to add those strings (lines) to one another but connected by '\n' character? – Pati K Oct 08 '16 at 19:54