harmony 鸿蒙@ohos.url (URL String Parsing)

2022-08-09 浏览 (834)

@ohos.url (URL String Parsing)

NOTE

The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import Url from '@ohos.url'

URLParams9+

constructor9+

constructor(init?: string[][]|Record<string, string>|string|URLParams)

A constructor used to create a URLParams instance.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
initstring[][] |Record<string, string> |string |URLParamsNoInput parameter objects, which include the following:
- string[][]: two-dimensional string array
- Record<string, string>: list of objects
- string: string
- URLParams: object
The default value is null.

Example

let objectParams = new Url.URLParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]);
let objectParams1 = new Url.URLParams({"fod" : '1' , "bard" : '2'});
let objectParams2 = new Url.URLParams('?fod=1&bard=2');
let urlObject = Url.URL.parseURL('https://developer.mozilla.org/?fod=1&bard=2');
let params = new Url.URLParams(urlObject.search);

append9+

append(name: string, value: string): void

Appends a key-value pair into the query string.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesKey of the key-value pair to append.
valuestringYesValue of the key-value pair to append.

Example

let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLParams(urlObject.search.slice(1));
paramsObject.append('fod', '3');

delete9+

delete(name: string): void

Deletes key-value pairs of the specified key.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesKey of the key-value pairs to delete.

Example

let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLParams(urlObject.search.slice(1));
paramsObject.delete('fod');

getAll9+

getAll(name: string): string[]

Obtains all the values based on the specified key.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesTarget key.

Return value

TypeDescription
string[]All the values obtained.

Example

let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2');
let params = new Url.URLParams(urlObject.search.slice(1));
params.append('fod', '3'); // Add a second value for the fod parameter.
console.log(params.getAll('fod').toString()) // Output ["1","3"].

entries9+

entries(): IterableIterator<[string, string]>

Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
IterableIterator<[string, string]>ES6 iterator.

Example

let searchParamsObject = new Url.URLParams("keyName1=valueName1&keyName2=valueName2");
let pair:Iterable<Object[]> = searchParamsObject.entries();
let arrayValue = Array.from(pair);
for (let pair of arrayValue) { // Show keyName/valueName pairs
  console.log(pair[0]+ ', '+ pair[1]);
}

forEach9+

forEach(callbackFn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void

Traverses the key-value pairs in the URLSearchParams instance by using a callback.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
callbackFnfunctionYesCallback invoked to traverse the key-value pairs in the URLSearchParams instance.
thisArgObjectNoValue of this to use when callbackFn is invoked. The default value is this object.

Table 1 callbackFn parameter description

NameTypeMandatoryDescription
valuestringYesValue that is currently traversed.
keystringYesKey that is currently traversed.
searchParamsObjectYesInstance that invokes the forEach method.

Example

const myURLObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); 
myURLObject.params.forEach((value, name, searchParams) => {  
    console.log(name, value, myURLObject.params === searchParams);
});

get9+

get(name: string): string|null

Obtains the value of the first key-value pair based on the specified key.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesKey specified to obtain the value.

Return value

TypeDescription
stringReturns the value of the first key-value pair if obtained.
nullReturns null if no value is obtained.

Example

let paramsObject = new Url.URLParams('name=Jonathan&age=18'); 
let name = paramsObject.get("name"); // is the string "Jonathan" 
let age = paramsObject.get("age"); // is the string "18"

has9+

has(name: string): boolean

Checks whether a key has a value.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesKey specified to search for its value.

Return value

TypeDescription
booleanReturns true if the value exists; returns false otherwise.

Example

let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLParams(urlObject.search.slice(1)); 
let result = paramsObject.has('bard');

set9+

set(name: string, value: string): void

Sets the value for a key. If key-value pairs matching the specified key exist, the value of the first key-value pair will be set to the specified value and other key-value pairs will be deleted. Otherwise, the key-value pair will be appended to the query string.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesKey of the value to set.
valuestringYesValue to set.

Example

let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLParams(urlObject.search.slice(1));
paramsObject.set('baz', '3'); // Add a third parameter.

sort9+

sort(): void

Sorts all key-value pairs contained in this object based on the Unicode code points of the keys and returns undefined. This method uses a stable sorting algorithm, that is, the relative order between key-value pairs with equal keys is retained.

System capability: SystemCapability.Utils.Lang

Example

let searchParamsObject = new Url.URLParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object
searchParamsObject.sort(); // Sort the key/value pairs
console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=4&c=3&d=2

keys9+

keys(): IterableIterator<string>

Obtains an ES6 iterator that contains the keys of all the key-value pairs.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
IterableIterator<string>ES6 iterator that contains the keys of all the key-value pairs.

Example

let searchParamsObject = new Url.URLParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing
let keys = Array.from(searchParamsObject.keys());
for (let key of keys) { // Output key-value pairs
  console.log(key);
}

values9+

values(): IterableIterator<string>

Obtains an ES6 iterator that contains the values of all the key-value pairs.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
IterableIterator<string>ES6 iterator that contains the values of all the key-value pairs.

Example

let searchParams = new Url.URLParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing
let values = Array.from(searchParams.values());
for (let value of values) {
  console.log(value);
}

[Symbol.iterator]9+

[Symbol.iterator](): IterableIterator<[string, string]>

Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
IterableIterator<[string, string]>ES6 iterator.

Example

const paramsObject = new Url.URLParams('fod=bay&edg=bap');
let iter: Iterable<Object[]> = paramsObject[Symbol.iterator]();
let pairs = Array.from(iter);
for (let pair of pairs) {
  console.log(pair[0] + ', ' + pair[1]);
}

tostring9+

toString(): string

Obtains search parameters that are serialized as a string and, if necessary, percent-encodes the characters in the string.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
stringString of serialized search parameters, which is percent-encoded if necessary.

Example

let url = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2');
let params = new Url.URLParams(url.search.slice(1)); 
params.append('fod', '3');
console.log(params.toString());

URL

Attributes

System capability: SystemCapability.Utils.Lang

NameTypeReadableWritableDescription
hashstringYesYesString that contains a harsh mark (#) followed by the fragment identifier of a URL.
hoststringYesYesHost information in a URL.
hostnamestringYesYesHostname (without the port) in a URL.
hrefstringYesYesString that contains the whole URL.
originstringYesNoRead-only string that contains the Unicode serialization of the origin of the represented URL.
passwordstringYesYesPassword in a URL.
pathnamestringYesYesPath in a URL.
portstringYesYesPort in a URL.
protocolstringYesYesProtocol in a URL.
searchstringYesYesSerialized query string in a URL.
searchParams(deprecated)URLSearchParamsYesNoURLSearchParams object allowing access to the query parameters in a URL.
- NOTE: This attribute is supported since API version 7 and is deprecated since API version 9. You are advised to use params9+ instead.
params9+URLParamsYesNoURLParams object allowing access to the query parameters in a URL.
usernamestringYesYesUsername in a URL.

constructor(deprecated)

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use parseURL9+ instead.

constructor(url: string, base?: string|URL)

Creates a URL.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
urlstringYesInput object.
basestring |URLNoInput parameter, which can be any of the following:
- string: string
- URL: string or object
The default value is an empty string or an empty object.

Example

let mm = 'https://username:password@host:8080';
let a = new Url.URL("/", mm); // Output 'https://username:password@host:8080/';
let b = new Url.URL(mm); // Output 'https://username:password@host:8080/';
new Url.URL('path/path1', b); // Output 'https://username:password@host:8080/path/path1';
let c = new Url.URL('/path/path1', b);  // Output 'https://username:password@host:8080/path/path1'; 
new Url.URL('/path/path1', c); // Output 'https://username:password@host:8080/path/path1';
new Url.URL('/path/path1', a); // Output 'https://username:password@host:8080/path/path1';
new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1
new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL
new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL
new Url.URL('https://www.example.com', ); // Output https://www.example.com/
new Url.URL('https://www.example.com', b); // Output https://www.example.com/

constructor9+

constructor()

A no-argument constructor used to create a URL. It returns a URL object after parseURL is called. It is not used independently.

System capability: SystemCapability.Utils.Lang

parseURL9+

static parseURL(url : string, base?: string|URL): URL

Parses a URL.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
urlstringYesInput object.
basestring |URLNoInput parameter, which can be any of the following:
- string: string
- URL: string or object
The default value is an empty string or an empty object.

Error codes

For details about the error codes, see Utils Error Codes.

IDError Message
10200002Invalid url string.

Example

let mm = 'https://username:password@host:8080';
let url = Url.URL.parseURL(mm); 
let result = url.toString(); // Output 'https://username:password@host:8080/'

tostring

toString(): string

Converts the parsed URL into a string.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
stringWebsite address in a serialized string.

Example

const url = Url.URL.parseURL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da');
let result = url.toString();

toJSON

toJSON(): string

Converts the parsed URL into a JSON string.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
stringWebsite address in a serialized string.

Example

const url = Url.URL.parseURL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da');
let result = url.toJSON();

URLSearchParams(deprecated)

constructor(deprecated)

constructor(init?: string[][]|Record<string, string>|string|URLSearchParams)

A constructor used to create a URLSearchParams instance.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.constructor9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
initstring[][] |Record<string, string> |string |URLSearchParamsNoInput parameter objects, which include the following:
- string[][]: two-dimensional string array
- Record<string, string>: list of objects
- string: string
- URLSearchParams: object
The default value is null.

Example

let objectParams = new Url.URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]);
let objectParams1 = new Url.URLSearchParams({"fod" : '1' , "bard" : '2'});
let objectParams2 = new Url.URLSearchParams('?fod=1&bard=2');
let urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2');
let params = new Url.URLSearchParams(urlObject.search);

append(deprecated)

append(name: string, value: string): void

Appends a key-value pair into the query string.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.append9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesKey of the key-value pair to append.
valuestringYesValue of the key-value pair to append.

Example

let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.append('fod', '3');

delete(deprecated)

delete(name: string): void

Deletes key-value pairs of the specified key.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.delete9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesKey of the key-value pairs to delete.

Example

let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsobject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsobject.delete('fod');

getAll(deprecated)

getAll(name: string): string[]

Obtains all the key-value pairs based on the specified key.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.getAll9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesTarget key.

Return value

TypeDescription
string[]All key-value pairs matching the specified key.

Example

let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let params = new Url.URLSearchParams(urlObject.search.slice(1));
params.append('fod', '3'); // Add a second value for the fod parameter.
console.log(params.getAll('fod').toString()) // Output ["1","3"].

entries(deprecated)

entries(): IterableIterator<[string, string]>

Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.entries9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
IterableIterator<[string, string]>ES6 iterator.

Example

let searchParamsObject = new Url.URLSearchParams("keyName1=valueName1&keyName2=valueName2");
let iter: Iterable<Object[]> = searchParamsObject.entries();
let pairs = Array.from(iter);
for (let pair of pairs) { // Show keyName/valueName pairs
  console.log(pair[0]+ ', '+ pair[1]);
}

forEach(deprecated)

forEach(callbackFn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void

Traverses the key-value pairs in the URLSearchParams instance by using a callback.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.forEach9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
callbackFnfunctionYesCallback invoked to traverse the key-value pairs in the URLSearchParams instance.
thisArgObjectNoValue of this to use when callbackFn is invoked. The default value is this object.

Table 1 callbackFn parameter description

NameTypeMandatoryDescription
valuestringYesValue that is currently traversed.
keystringYesKey that is currently traversed.
searchParamsObjectYesInstance that invokes the forEach method.

Example

const myURLObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); 
myURLObject.searchParams.forEach((value, name, searchParams) => {  
    console.log(name, value, myURLObject.searchParams === searchParams);
});

get(deprecated)

get(name: string): string|null

Obtains the value of the first key-value pair based on the specified key.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.get9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesKey specified to obtain the value.

Return value

TypeDescription
stringReturns the value of the first key-value pair if obtained.
nullReturns null if no value is obtained.

Example

let paramsObject = new Url.URLSearchParams('name=Jonathan&age=18');
let name = paramsObject.get("name"); // is the string "Jonathan"
let age = paramsObject.get("age"); // is the string '18'

has(deprecated)

has(name: string): boolean

Checks whether a key has a value.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.has9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesKey specified to search for its value.

Return value

TypeDescription
booleanReturns true if the value exists; returns false otherwise.

Example

let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1)); 
paramsObject.has('bard') === true;

set(deprecated)

set(name: string, value: string): void

Sets the value for a key. If key-value pairs matching the specified key exist, the value of the first key-value pair will be set to the specified value and other key-value pairs will be deleted. Otherwise, the key-value pair will be appended to the query string.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.set9+ instead.

System capability: SystemCapability.Utils.Lang

Parameters

NameTypeMandatoryDescription
namestringYesKey of the value to set.
valuestringYesValue to set.

Example

let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.set('baz', '3'); // Add a third parameter.

sort(deprecated)

sort(): void

Sorts all key-value pairs contained in this object based on the Unicode code points of the keys and returns undefined. This method uses a stable sorting algorithm, that is, the relative order between key-value pairs with equal keys is retained.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.sort9+ instead.

System capability: SystemCapability.Utils.Lang

Example

let searchParamsObject = new Url.URLSearchParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object
searchParamsObject.sort(); // Sort the key/value pairs
console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=4&c=3&d=2

keys(deprecated)

keys(): IterableIterator<string>

Obtains an ES6 iterator that contains the keys of all the key-value pairs.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.keys9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
IterableIterator<string>ES6 iterator that contains the keys of all the key-value pairs.

Example

let searchParamsObject = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing
let keys = Array.from(searchParamsObject.keys());
for (let key of keys) { // Output key-value pairs
  console.log(key);
}

values(deprecated)

values(): IterableIterator<string>

Obtains an ES6 iterator that contains the values of all the key-value pairs.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.values9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
IterableIterator<string>ES6 iterator that contains the values of all the key-value pairs.

Example

let searchParams = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing
let values = Array.from(searchParams.values());
for (let value of values) {
  console.log(value);
}

[Symbol.iterator](deprecated)

[Symbol.iterator](): IterableIterator<[string, string]>

Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.[Symbol.iterator]9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
IterableIterator<[string, string]>ES6 iterator.

Example

const paramsObject = new Url.URLSearchParams('fod=bay&edg=bap');
let iter: Iterable<Object[]> = paramsObject[Symbol.iterator]();
let pairs = Array.from(iter);
for (let pair of pairs) {
  console.log(pair[0] + ', ' + pair[1]);
}

tostring(deprecated)

toString(): string

Obtains search parameters that are serialized as a string and, if necessary, percent-encodes the characters in the string.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use URLParams.tostring9+ instead.

System capability: SystemCapability.Utils.Lang

Return value

TypeDescription
stringString of serialized search parameters, which is percent-encoded if necessary.

Example

let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let params = new Url.URLSearchParams(url.search.slice(1)); 
params.append('fod', '3');
console.log(params.toString());

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/47b37201a91c4b34b19f62e6557d5d55