이 method는 순수자바스트크립트에서도 사용이 가능하며, 고로 react에서도 사용 가능.
const naverUrl = new URL('https://openapi.naver.com/v1/search/book.json');
// Set 'query' parameter
naverUrl.searchParams.set('query', 'your_search_term');
// Set additional parameters as needed
naverUrl.searchParams.set('start', 1); // First page of results
naverUrl.searchParams.set('display', 10); // Number of results per page
console.log(naverUrl.toString());
// Output: https://openapi.naver.com/v1/search/book.json?query=your_search_term&start=1&display=10
Other Methods in URLSearchParams:
get(key): Retrieves the value of a specific query parameter.
has(key): Checks if a specific query parameter exists.
delete(key): Removes a specific query parameter.
entries(): Returns an iterator over all query parameters.
forEach(callback): Iterates over all query parameters and calls the callback function.
get(key) : This method retrieves the value of a specific query parameter.
const url = new URL('https://www.example.com/search?q=books&page=2');
const searchTerm = url.searchParams.get('q'); // searchTerm will be 'books'
const pageNumber = url.searchParams.get('page'); // pageNumber will be '2'
console.log('Search term:', searchTerm);
console.log('Page number:', pageNumber);
has(key): This method checks if a specific query parameter exists.
const url = new URL('https://www.example.com/search?q=books');
if (url.searchParams.has('q')) {
console.log('The "q" parameter exists');
} else {
console.log('The "q" parameter does not exist');
}
delete(key): This method removes a specific query parameter.
const url = new URL('https://www.example.com/search?q=books&sort=newest');
url.searchParams.delete('sort'); // Removes the 'sort' parameter
console.log(url.toString()); // Output: https://www.example.com/search?q=books
entries(): This method returns an iterator over all query parameters.
const url = new URL('https://www.example.com/search?q=books&page=2'); for (const [key, value] of url.searchParams.entries()) { console.log(key, value); // Output: 'q', 'books' and 'page', '2' }
forEach(callback): This method iterates over all query parameters and calls the callback function for each one.
const url = new URL('https://www.example.com/search?q=books&page=2');
url.searchParams.forEach((value, key) => {
console.log(key, value); // Same output as using `entries()`
});
'나의 FE피봇이야기 > Javascript' 카테고리의 다른 글
[Javascript] function and ( ) =>{ } (0) | 2024.02.17 |
---|---|
[Javascript] fetch with post (0) | 2024.02.17 |
[JavaScript]ScrollY? versus pageYoffset? (0) | 2024.01.24 |
[React] 간단한 서버 세팅 하는 법 (0) | 2024.01.19 |
[Javascript] vue.js computed와 methods (0) | 2024.01.08 |