How to use url

Comprehensive url code examples:

How to use url.trim:

9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
module.exports = function (url) {
	if (typeof url !== 'string') {
		throw new TypeError('Expected a string, got ' + typeof url);
	}


	url = url.trim();


	if (/^\.*\/|^(?!localhost)\w+:/.test(url)) {
		return url;
	}

How to use url.password:

6002
6003
6004
6005
6006
6007
6008
6009
6010
6011

var result = protocol + (url.slashes || isSpecial(url.protocol) ? '//' : '');

if (url.username) {
  result += url.username;
  if (url.password) result += ':'+ url.password;
  result += '@';
}

result += url.host + url.pathname;

How to use url.port:

5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
  break;

case 'hostname':
  url[part] = value;

  if (url.port) value += ':'+ url.port;
  url.host = value;
  break;

case 'host':

How to use url.startsWith:

713
714
715
716
717
718
719
720
721
722
newWindow.webContents.setWindowOpenHandler(({ url }) => {
  //console.log( 'url=' + url );
  //console.log( 'frameName=' + frameName );
  //console.log( 'additionalFeatures=' + additionalFeatures );

  if( url.startsWith(interspec_url) ) {
    //Lets prevent a weird popup window that the user has to close...
    //  I think this is because InterSpec targets a new window for downloads.
    newWindow.webContents.downloadURL(url);
  } else {

How to use url.auth:

5875
5876
5877
5878
5879
5880
5881
5882
5883
//
// Parse down the `auth` for the username and password.
//
url.username = url.password = '';
if (url.auth) {
  instruction = url.auth.split(':');
  url.username = instruction[0] || '';
  url.password = instruction[1] || '';
}

How to use url.pathname:

5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
// If the URL is relative, resolve the pathname against the base URL.
//
if (
    relative
  && location.slashes
  && url.pathname.charAt(0) !== '/'
  && (url.pathname !== '' || location.pathname !== '')
) {
  url.pathname = resolve(url.pathname, location.pathname);
}

How to use url.username:

6001
6002
6003
6004
6005
6006
6007
6008
6009
if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';

var result = protocol + (url.slashes || isSpecial(url.protocol) ? '//' : '');

if (url.username) {
  result += url.username;
  if (url.password) result += ':'+ url.password;
  result += '@';
}

How to use url.toString:

3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120


  // Implicit POST if we have not specified a method but have a body
  options.method = options.body && !options.method ? 'POST' : (options.method || 'GET').toUpperCase();


  // Stringify URL
  options.url = url.toString(stringifyQueryString);


  return options;
};

How to use url.protocol:

187
188
189
190
191
192
193
194
195
196

const requestHeaders = Object.assign({
	':authority': url.host,
	':method': 'GET',
	':path': url.pathname,
	':scheme': url.protocol.substring(0, url.protocol.length - 1),
}, {
	'user-agent': randomHeaders['user-agent'],
	'accept': randomHeaders['accept'],
	'accept-language': randomHeaders['accept-language'],

How to use url.replace:

9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
if (typeof url !== 'string' && typeof url !== 'object') {
	throw new Error(`Parameter \`url\` must be a string or object, not ${typeof url}`);
}

if (typeof url === 'string') {
	url = url.replace(/^unix:/, 'http://$&');
	url = urlParseLax(url);

	if (url.auth) {
		throw new Error('Basic authentication must be done with auth option');

How to use url.Url:

11
12
13
14
15
16
17
18
19
20
21
22
 * @private
 */


var url = require('url')
var parse = url.parse
var Url = url.Url


/**
 * Module exports.
 * @public

How to use url.default:

2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
  cwd = import_node_process3.default.cwd(),
  path: path_ = import_node_process3.default.env[pathKey()],
  execPath = import_node_process3.default.execPath
} = options;
let previous;
const cwdString = cwd instanceof URL ? import_node_url.default.fileURLToPath(cwd) : cwd;
let cwdPath = import_node_path7.default.resolve(cwdString);
const result = [];
while (previous !== cwdPath) {
  result.push(import_node_path7.default.join(cwdPath, "node_modules/.bin"));

How to use url.substr:

411
412
413
414
415
416
417
418
419
420
while (imageMatch = imageRe.exec(content)) {
    const url = imageMatch[1];
    const inlineImageMatch = /^data:image\/[a-z]+;base64,/.exec(url);

    if (inlineImageMatch) {
        const imageBase64 = url.substr(inlineImageMatch[0].length);
        const imageBuffer = Buffer.from(imageBase64, 'base64');

        const imageService = require('../services/image');
        const {note} = imageService.saveImage(noteId, imageBuffer, "inline image", true, true);

How to use url.toLowerCase:

423
424
425
426
427
428
429
430
431

    content = `${content.substr(0, imageMatch.index)}<img src="api/images/${note.noteId}/${sanitizedTitle}"${content.substr(imageMatch.index + imageMatch[0].length)}`;
}
else if (!url.includes('api/images/')
    // this is an exception for the web clipper's "imageId"
    && (url.length !== 20 || url.toLowerCase().startsWith('http'))) {

    if (url in imageUrlToNoteIdMapping) {
        const imageNote = becca.getNote(imageUrlToNoteIdMapping[url]);

How to use url.slice:

1145
1146
1147
1148
1149
1150
1151
1152
1153

if (serializedParams) {
  const hashmarkIndex = url.indexOf("#");

  if (hashmarkIndex !== -1) {
    url = url.slice(0, hashmarkIndex);
  }
  url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}

How to use url.split:

7536
7537
7538
7539
7540
7541
7542
7543
7544
// Back slashes before the query string get converted to forward slashes
// See: https://code.google.com/p/chromium/issues/detail?id=25916
var queryIndex = url.indexOf('?'),
    splitter =
        (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
    uSplit = url.split(splitter),
    slashRegex = /\\/g;
uSplit[0] = uSplit[0].replace(slashRegex, '/');
url = uSplit.join(splitter);

How to use url.URLSearchParams:

74
75
76
77
78
79
80
81
82
83
) {
  if (callback == null) {
    callback = function () {}
  }
  const u = new URL(`${Settings.apis.clsi.url}/project/${projectId}/status`)
  u.search = new URLSearchParams({
    compileGroup,
    compileBackendClass,
  }).toString()
  request.post(u.href, (err, res, body) => {

How to use url.fileURLToPath:

11
12
13
14
15
16
17
18
19
20
const path = require('path')
const url = require('url')

app.whenReady().then(() => {
  protocol.registerFileProtocol('atom', (request, callback) => {
    const filePath = url.fileURLToPath('file://' + request.url.slice('atom://'.length))
    callback(filePath)
  })
})
```

How to use url.indexOf:

7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
}

// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://code.google.com/p/chromium/issues/detail?id=25916
var queryIndex = url.indexOf('?'),
    splitter =
        (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
    uSplit = url.split(splitter),
    slashRegex = /\\/g;

How to use url.origin:

214
215
216
217
218
219
220
221
222
223
object's properties will be modified.

If the value assigned to the `href` property is not a valid URL, a `TypeError`
will be thrown.

#### url.origin

* {string}

Gets the read-only serialization of the URL's origin.

How to use url.host:

147
148
149
150
151
152
153
154
155
156
Invalid URL characters included in the value assigned to the `hash` property
are [percent-encoded][]. Note that the selection of which characters to
percent-encode may vary somewhat from what the [`url.parse()`][] and
[`url.format()`][] methods would produce.

#### url.host

* {string}

Gets and sets the host portion of the URL.

How to use url.href:

187
188
189
190
191
192
193
194
195
196
// Prints https://example.com:81/foo
```

Invalid hostname values assigned to the `hostname` property are ignored.

#### url.href

* {string}

Gets and sets the serialized URL.

How to use url.hostname:

166
167
168
169
170
171
172
173
174
175
// Prints https://example.com:82/foo
```

Invalid host values assigned to the `host` property are ignored.

#### url.hostname

* {string}

Gets and sets the hostname portion of the URL. The key difference between

How to use url.hash:

125
126
127
128
129
130
131
132
133
134
```

*Note*: This feature is only available if the `node` executable was compiled
with [ICU][] enabled. If not, the domain names are passed through unchanged.

#### url.hash

* {string}

Gets and sets the fragment portion of the URL.

How to use url.resolve:

122
123
124
125
126
127
128
129
130
131
  return reject(NOT_MULTIVARIANT_ERROR_MSG);
}

for (let i = 0; i < m3u.items.StreamItem.length; i++) {
  const streamItem = m3u.items.StreamItem[i];
  const mediaManifestUrl = url.resolve(baseUrl, streamItem.get("uri"));
  mediaManifestPromises.push(
    this.loadMediaManifest(mediaManifestUrl, streamItem.get("bandwidth"), _injectMediaManifest)
  );
}

How to use url.pathToFileURL:

175
176
177
178
179
180
181
182
183
184
let parentURL;
try {
  const { pathToFileURL } = require('url');
  // Adding `/repl` prevents dynamic imports from loading relative
  // to the parent of `process.cwd()`.
  parentURL = pathToFileURL(path.join(process.cwd(), 'repl')).href;
} catch {
}

// Remove all "await"s and attempt running the script

How to use url.format:

108
109
110
111
112
113
114
115
116
117
    })
    .catch(e => log.debug(e)); // Ignore errors, since this is non-essential
});

mainWindow.loadURL(
  url.format({
    pathname: path.join(__dirname, "../public/index.html"),
    protocol: "file",
    slashes: true
  })

How to use url.parse:

176
177
178
179
180
181
182
183
184
185
186
    await _extractFile({ src, dest, fileExt, overwrite });
    await fse.remove(src);
};


const _parseGitUrl = (url) => {
    const parsedUrl = urlLib.parse(url);
    const [, owner, repo] = parsedUrl.pathname.split('/');
    return {
        owner,
        repo,

How to use url.URL:

171
172
173
174
175
176
177
178
179
are supported.

```js
const fs = require('fs');
const { URL } = require('url');
const fileUrl = new URL('file:///tmp/hello');

fs.readFileSync(fileUrl);
```