Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a JavaScript function to extract all hyperlinks (<href=…>) from given text.
- The text comes as array of strings, passed as parameter to your function. Print at the console
- the href values in the text. The input text is standard HTML code. It may hold many tags and can be formatted
- in many different forms (with or without whitespace). The <a> elements may have many attributes, not only href.
- You should extract only the values of the href attributes of all <a> elements.
- Print at the console the href values in the text, each at a separate line, in the order they come from the input.
- The input will be well formed HTML fragment (all tags and attributes will be correctly closed).
- Attribute values will never hold tags and hyperlinks, e.g. "<img alt='<a href="hello">' />" is invalid.
- Commented links are also extracted. */
- "use strict";
- function hyperlinksExtractor(args) {
- var htmlCode = args.join('\n');
- var pattern = /<a\s+([^>]+\s+)?href\s*=\s*('([^']*)'|"([^"]*)|([^\s>]+))[^>]*>/g;
- var matcher;
- while (matcher = pattern.exec(htmlCode)) {
- console.log(matcher[3] ? matcher[3] : matcher[4] ? matcher[4] : matcher[5]);
- }
- }
- hyperlinksExtractor(['<a href="http://softuni.bg" class="new"></a>']);
- hyperlinksExtractor(['<p>This text has no links</p>']);
- hyperlinksExtractor([
- '<!DOCTYPE html>',
- '<html>',
- '<head>',
- ' <title>Hyperlinks</title>',
- ' <link href="theme.css" rel="stylesheet" />',
- '</head>',
- '<body>',
- '<ul><li><a href="/" id="home">Home</a></li><li><a',
- ' class="selected" href="/courses">Courses</a>',
- '</li><li><a href = ',
- '\'/forum\' >Forum</a></li><li><a class="href"',
- 'onclick="go()" href= "#">Forum</a></li>',
- '<li><a id="js" href =',
- '"javascript:alert(\'hi\')" class="new">click</a></li>',
- '<li><a id=\'nakov\' href =',
- '\'http://www.nakov.com\' class=\'new\'>nak</a></li></ul>',
- '<a href="#"></a>',
- '<a id="href">href=\'fake\'<img src=\'http://abv.bg/i.gif\' ',
- 'alt=\'abv\'/></a><a href="#"><a href=\'hello\'></a>',
- '<!-- This code is commented:',
- ' <a href="#commented">commentex hyperlink</a> -->',
- '</body>'
- ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement