0

Sample String:

var demoString="Extract the URLs and Lables from String Google:https://www.google.com Yahoo:http://yahoo.com";

I would like to able to extract some portion of the provide string like(Google,https://www.google.com,Yahoo,http://yahoo.com)

How can I achieve this with JavaScript?

Lova Chittumuri
  • 2,994
  • 1
  • 30
  • 33

1 Answers1

1

You can achieve this using a Regex expression. These expressions specify rules for matching text.

In this case you could use the following Regex expression (you can try it here):

[A-Za-z0-9]+\:https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

  • [A-Za-z0-9]+ matches the site name (with no spaces)
  • \: matches the colon
  • https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*) matches any URL starting the http or https (taken from this answer: https://stackoverflow.com/a/3809435/1943263)

To use this in Javascript you would do something like this:

var demoString="Extract the URLs and Lables from String Google:https://www.google.com Yahoo:http://yahoo.com";

var regexPattern = /([A-Za-z0-9]+)\:(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))/g;

var matches = demoString.match(regexPattern);

console.log(matches);
Ivan Kahl
  • 598
  • 2
  • 11