0

I am trying to write code to parse URL using Javascript parseURL function

Input are some of the URL

1.http://www.cnn.com/index.html
2.https://yahoo.com/movies/index.html?refresh=1

Expected Output

1.http,www.cnn.com
2.https,yahoo.com,refresh=1

I have tried to write code

process.stdin.resume();
process.stdin.setEncoding('utf8');

var stdin = '';
process.stdin.on('data', function parse(chunk) {
  stdin += chunk;
}).on('end', function() {
  var lines = stdin.trim().split('\n');
  for(var i=0; i<lines.length; i++) {
    process.stdout.write(lines[i]);
  }
});

But I am unable to get expected output

1
  • Have you considered using the standard url package that's built-into node.js Commented Jun 14, 2019 at 20:51

1 Answer 1

2

The pattern /^.+(?=:\/\/)|(?<=:\/\/)[^\/]+|(?<=\?).+$/g enumerates the following three possibilities, matching any of them with alternation:

  1. the beginning of the string up until ://
  2. :// until the next /
  3. everything after a ? until the end of the string.

const pattern = /^.+(?=:\/\/)|(?<=:\/\/)[^\/]+|(?<=\?).+$/g;
[
  "1.http://www.cnn.com/index.html",
  "2.https://yahoo.com/movies/index.html?refresh=1"
].forEach(e => console.log(e.match(pattern)));

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for quick reply, could you please help me figure out where should I add this in my code? What changes should I make in the code? Thank you
Hard to say--it looks like you're returning an object with 4 properties, but only 2-3 appear in your split strings. You'll need to provide more information, but basically you have an array of 2-3 elements and can assign them to your object properties as you wish.
Okay I have edited the code, could you suggest where should I add your code? In the end I just want a seperate String
Is each chunk a single line? If so, you can put the code in the listener. Or, take all the input, then operate on the result string s. Split it by lines and use the regex on each line as I'm doing. Again, it's hard to say, because I don't know what your stdin is accepting. But basically, that's all boilerplate--just show what s and/or chunk looks like exactly and there's no ambiguity.
Yes each chunk is a single line
|

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.