Take the url and change the value?

Asked

Viewed 67 times

1

Site node have a function to sort higher and lower value. I need to take the current url and change a value that is within it.

Current URL: http://localhost/search.php? type=locacao&ordem=vx&tim%5B%5D=Casa&bar%5B%5D=Brazil&pagina=1

I need to take the value order=vx and change to order=v, and I need to do this within this function below. Because it is she who makes action.

$("#sort-type").change(function() {

            var url = window.location.href;

            $("#order").val( $(this).val() )
            $("#formFilter").submit();
        });

How can I do that within that function?

  • This url is from your page?

3 answers

1


0

There are a few ways to do this. You can create a function to give a replace in your current URL, passing as parameter the URL itself, the parameter name and the value you want to put in it. This example is here in this answer of Soen. See below for an example:

function replaceParam(url, paramName, paramValue)
{
    if (paramValue == null) {
        paramValue = '';
    }
    var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
    if (url.search(pattern)>=0) {
        return url.replace(pattern,'$1' + paramValue + '$2');
    }
    url = url.replace(/[?#]$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

var url = window.location.href;

console.log(replaceParam(url, "ordem", "v"))

0

Create a utility function that uses Web Apis URL and Urlsearchparam. These Apis work in all browsers except possibly Internet Explorer (for a change). The example below can be used anywhere and has the following behavior:

  • if the parameter does not exist, then insert it at the end
  • if there are multiple (repeated) parameters, then all of them are deleted and only one is replaced

function changeParam(url, param, value) {
    const urlObject = new URL(url)
    const urlSearchParams = urlObject.searchParams
    urlSearchParams.set(param, value)

    return urlObject.href
}

const tests = [
  {
      href: 'http://localhost/busca.php?tipo=locacao&ordem=vx&tim%5B%5D=Casa&bar%5B%5D=BRASIL&pagina=1',
      param: 'ordem',
      value: 'valor do parâmetro "ordem"'
  },
  {
      href: 'http://www.example.com.br/foo/bar.php?q1=arg1&q2=arg2&q1=3#hash',
      param: 'q1',
      value: 'newQ1'
  },
  {
      href: window.location.href,
      param: 'nao_existe',
      value: 'não existe ainda'
  },
]

tests.forEach(({href, param, value}) => {
    console.log(changeParam(href, param, value))
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.