Javascript удалить get параметры

amorkovin / remove-get-param-from-url.js

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

// Удаляет указанный get-параметр из URL.
function removeGetParam ( url , paramName )
const parts = window . location . search . substr ( 1 ) . split ( «&» ) ;
let $_GET = < >;
for ( let i = 0 ; i < parts . length ; i ++ )
let temp = parts [ i ] . split ( «=» ) ;
$_GET [ decodeURIComponent ( temp [ 0 ] ) ] = decodeURIComponent ( temp [ 1 ] ) ;
>
const oldUrl = new URL ( url ) ;
let newSearch = » ;
let i = 1 ;
for ( let prop in $_GET )
if ( prop !== paramName )
newSearch = newSearch + ‘&’ + prop + ‘=’ + $_GET [ prop ] ;
>
i ++ ;
>
if ( newSearch )
newSearch = ‘?’ + newSearch . slice ( 1 ) ;
>
let newPathname = » ;
if ( oldUrl . pathname . length > 1 )
newPathname = oldUrl . pathname ;
>
const newUrl = oldUrl . origin + newPathname + newSearch ;
return newUrl ;
>

Источник

Как удалить get параметр с помощью js/jquery?

Помогите пожалуйста мне нужно удалить из адресной строки определенный get параметр, я уже пол дня лазяю по интернету и ничего не подходит/не работает, может кто-то помочь?

Простой 5 комментариев

wapster92

Может нужно лазать, а не лазЯть)
По первому же запросу удалить символ из строки почему-то находится ответ. Может ну его это программирование? Есть всякие доставки еды, там сильно думать не нужно

wapster92

Httdientee уточните: в результате хочется получить строку, или перенаправить браузер на новый адрес (без удалённого параметра), или просто переписать это в адресной строке браузера, но НЕ переправлять браузер (не вызывать перезагрузку страницы) ?

Сергей Соколов, просто переписать это в адресной строке браузера, но НЕ переправлять браузер (не вызывать перезагрузку страницы) ?

Первый – получить параметры запроса и удалить из них искомый. Это работа с апи URL и searchParams — там есть метод delete() для удаления параметра. В итоге из URL получим новую адресную строку без лишнего параметра.

Второй – заменить адресную строку, не перегружая страницу. Это работа с history API и методом pushState(), то что вовсю используется в одностраничных сайтах. Как бы переходишь по страницам, адрес меняется, но на деле страница не перегружается, а изменяется динамически.

const url = new URL(document.location); const searchParams = url.searchParams; searchParams.delete("test"); // удалить параметр "test" window.history.pushState(<>, '', url.toString());

Источник

Javascript удалить get параметры

Last updated: Jan 9, 2023
Reading time · 4 min

banner

# Table of Contents

# Remove the Query String from a URL in JavaScript

To remove the query string from a URL:

  1. Use the URL() constructor to create a URL object.
  2. Set the search property on the URL object to an empty string.
  3. Use the toString() method to convert the URL object to a string.
Copied!
const url = 'https://bobbyhadz.com/books?page=10#hash'; const urlObj = new URL(url); urlObj.search = ''; const result = urlObj.toString(); // 👇️ https://bobbyhadz.com/books#hash console.log(result);

The URL() constructor returns a newly created URL object that represents the URL it got passed as a parameter.

You can use the search property on the URL object to access or update the query string.

Copied!
const url = 'https://bobbyhadz.com/books?page=10#hash'; const urlObj = new URL(url); console.log(urlObj.search); // 👉️ ?page=10

The search property returns a string containing a ? followed by the parameters of the URL.

You can remove the query string from the URL by setting the search property to an empty string.

Copied!
const url = 'https://bobbyhadz.com/books?page=10#hash'; const urlObj = new URL(url); urlObj.search = ''; const result = urlObj.toString(); // 👇️ https://bobbyhadz.com/books#hash console.log(result);

The URL.toString() method returns a string containing the whole URL.

If you have to do this often, define a reusable function.

Copied!
function removeQueryString(url) const urlObj = new URL(url); urlObj.search = ''; return urlObj.toString(); > const url = 'https://bobbyhadz.com/books?page=10#hash'; const result = removeQueryString(url); console.log(result); // 👉️ https://bobbyhadz.com/books#hash

The function takes a URL as a parameter and removes the query string from the URL.

# Remove the query string and hash from a URL in JavaScript

You can use the same approach to remove the hash from the URL.

Simply set the hash property on the URL object to an empty string.

Copied!
const url = 'https://bobbyhadz.com/books?page=10#hash'; const urlObj = new URL(url); urlObj.search = ''; urlObj.hash = ''; const result = urlObj.toString(); // 👇️ https://bobbyhadz.com/books console.log(result);

The URL.hash property is a string containing a # followed by the fragment identifier of the URL

The property can be used to access or set the hash.

Copied!
const url = 'https://bobbyhadz.com/books?page=10#hash'; const urlObj = new URL(url); console.log(urlObj.hash); // 👉️ #hash

Setting the hash property to an empty string removes it from the URL, just like setting the search property removes the query string.

# Remove the query string from a URL using split()

This is a three-step process:

  1. Use the split() method to split the string on a question mark.
  2. Access the array element at index 0 .
  3. The first element is the part of the URL before the query string.
Copied!
const url = 'https://bobbyhadz.com/books?page=10#hash'; const result = url.split('?')[0]; console.log(result); // 👉️ "https://bobbyhadz.com/books"

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

Name Description
separator The pattern describing where each split should occur.
limit An integer used to specify a limit on the number of substrings to be included in the array.
Copied!
const url = 'https://bobbyhadz.com/books?page=10#hash'; // 👇️ ['https://bobbyhadz.com/books', 'page=10#hash'] console.log(url.split('?'));

The method returns an array containing 2 strings — the one before and the one after the question mark.

This solution also handles the scenario where the URL doesn’t contain a query string.

Copied!
const url = 'https://bobbyhadz.com/books'; const result = url.split('?')[0]; console.log(result); // 👉️ "https://bobbyhadz.com/books"

If you pass a substring that is not contained in the string, the split() method returns an array containing the entire string.

An alternative approach is to use the String.indexOf method to get the index of the question mark.

# Remove the query string from a URL using indexOf()

This is a two-step process:

  1. Use the indexOf() method to get the index of the question mark in the string.
  2. Use the slice() method to get the part of the string before the question mark.
Copied!
const url = 'https://bobbyhadz.com/books?page=10#hash'; const result = url.slice(0, url.indexOf('?')); console.log(result); // 👉️ "https://bobbyhadz.com/books"

The String.slice method extracts a section of a string and returns it, without modifying the original string.

The String.slice() method takes the following arguments:

Name Description
start index The index of the first character to include in the returned substring
end index The index of the first character to exclude from the returned substring

The indexOf method returns the index of the first occurrence of a substring in the string or -1 if the substring is not contained in the string.

This is a potential edge case that you need to handle if you pick this approach.

Copied!
const url = 'https://bobbyhadz.com/books'; let result = url; if (url.includes('?')) result = url.slice(0, url.indexOf('?')); > console.log(result); // 👉️ "https://bobbyhadz.com/books"

Our if statement handles the condition where the URL doesn’t contain a query string.

# Remove the query string but preserve the hash

If you need to remove the query string, but want to preserve the hash, concatenate two calls to the slice method.

Copied!
const url = 'https://bobbyhadz.com/books?page=10#hash'; const result = url.slice(0, url.indexOf('?')) + url.slice(url.indexOf('#')); console.log(result); // 👉️ "https://bobbyhadz.com/books#hash"

The first call to the slice() method gets the part of the URL before the query string.

The second call contains the string from the hash onwards.

When only a single argument is passed to the String.slice() method, the slice goes to the end of the string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to Change URL Query Parameters with Javascript

Search query parameters can be added, updated or deleted using Javascript URL and URLSearchParams objects.

To know how to get query parameters using URL and URLSearchParams , refer the tutorial Get URL Parameters with Javascript.

Edit / Update a Parameter

The value of a parameter can be updated with the set() method of URLSearchParams object.

After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.

The final new url can then be retrieved with the toString() method of the URL object.

var url = new URL('http://demourl.com/path?id=100&topic=main'); var search_params = url.searchParams; // new value of "id" is set to "101" search_params.set('id', '101'); // change the search property of the main url url.search = search_params.toString(); // the new url string var new_url = url.toString(); // output : http://demourl.com/path?id=101&topic=main console.log(new_url); 

Add a New Parameter

  • The set() method can be used to add a new parameter — the parameter is added if it does exist, otherwise its value is changed.
var url = new URL('http://demourl.com/path?id=100'); var search_params = url.searchParams; // add "topic" parameter search_params.set('topic', 'main'); url.search = search_params.toString(); var new_url = url.toString(); // output : http://demourl.com/path?id=100&topic=main console.log(new_url); 
var url = new URL('http://demourl.com/path?topic=main'); var search_params = url.searchParams; search_params.append('id', '101'); search_params.append('id', '102'); url.search = search_params.toString(); var new_url = url.toString(); // output : http://demourl.com/path?id=100&id=101&id=102&topic=main console.log(new_url); 

Delete a Parameter By Name

The delete() method can be used to remove a parameter from the url.

Remove All Parameters

All query parameters can be cleared from the url by setting search property of the URL object to blank.

var url = new URL('http://demourl.com/path?topic=main'); // set search property to blank url.search = ''; var new_url = url.toString(); // output : http://demourl.com/path console.log(new_url); 

Источник

Читайте также:  Sign Up
Оцените статью