source

url 매개 변수를 javascript/jquery로 대체하는 방법은 무엇입니까?

nicesource 2023. 8. 27. 09:39
반응형

url 매개 변수를 javascript/jquery로 대체하는 방법은 무엇입니까?

효율적인 방법을 찾고 있었지만 찾을 수 없었습니다. 기본적으로 필요한 것은 다음과 같은 URL입니다.

http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100

URL 경할수좋겠습에 있는 할 수 있으면 src 또는 , 합니까?jquery 스크립트 또jquery 사른을값변진가수매, 이가니까합능이것jav개를?

다음 솔루션은 다른 답변을 결합하고 일부 특수 사례를 처리합니다.

  • 매개 변수가 원래 URL에 없습니다.
  • 매개 변수는 유일한 매개 변수입니다.
  • 매개 변수가 처음 또는 마지막입니다.
  • 새 매개 변수 값이 이전 매개 변수 값과 동일합니다.
  • .?
  • \b 변수가 paramName과 일치하지 .

솔루션:

function replaceUrlParam(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;
}

알려진 제한 사항:

  • paramValue를 null로 설정하여 매개 변수를 지우지 않고 빈 문자열로 설정합니다.매개 변수를 제거하려면 https://stackoverflow.com/a/25214672 을 참조하십시오.

이제 그것은 네이티브 JS로 가능합니다.

var href = new URL('https://google.com?q=cats');
href.searchParams.set('q', 'dogs');
console.log(href.toString()); // https://google.com/?q=dogs

이것이 더 나은 해결책이 아닐까요?

var text = 'http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100';
var newSrc = 'www.google.com';
var newText = text.replace(/(src=).*?(&)/,'$1' + newSrc + '$2');

편집:

코드에 약간의 명확성을 추가하고 결과 링크에 'src'를 유지했습니다.

$1의 첫 번째 부분을 나타냅니다.() (계속)src=그리고.$2 번부나다니타냅분을째▁▁part▁repres 두 번째 부분을 .() (계속)&따라서 이것은 당신이 다음 사이의 값을 변경할 것임을 나타냅니다.src그리고.& 더 명확하게는, 해야 : 보명확다같습다니과음는게하다다같▁more니▁this.

src='changed value'& // this is to be replaced with your original url

모든 발생 항목을 대체하기 위한 추가 기능:

의 매개 가 여러 개 경우 regex 플래그에 할 수 .text.replace(/(src=).*?(&)/g,'$1' + newSrc + '$2');그러면 동일한 이름을 공유하는 매개 변수의 모든 값이 바뀝니다.

Javascript는 이제 url 매개 변수를 처리하는 데 매우 유용한 기능을 제공합니다. URLSearchParams

var searchParams = new URLSearchParams(window.location.search);
searchParams.set('src','newSrc')
var newParams = searchParams.toString()

최신 브라우저(IE9 이하를 제외한 모든 것)에서는 새로운 URL api를 통해 이제 우리의 삶이 조금 더 쉬워졌습니다.

var url = new window.URL(document.location); // fx. http://host.com/endpoint?abc=123
url.searchParams.set("foo", "bar");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=bar
url.searchParams.set("foo", "ooft");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=ooft

수정된 스테닉스의 코드는 완벽하지 않지만 다음과 같이 제공된 매개 변수를 포함하는 url에 매개 변수가 있는 경우를 처리합니다.

/search?searchquery=text and 'query' is provided.

이 경우 검색 쿼리 매개 변수 값이 변경됩니다.

코드:

function replaceUrlParam(url, paramName, paramValue){
    var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
    var newUrl=url
    if(url.search(pattern)>=0){
        newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
    }
    else{
        newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
    }
    return newUrl
}
// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
 
// Set new or modify existing parameter value. 
queryParams.set("myParam", "myValue");
 
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());

replaceState()를 사용하여 현재 기록 항목을 수정하는 대신 pushState() 메서드를 사용하여 새 기록 항목을 만들 수 있습니다.

history.pushState(null, null, "?"+queryParams.toString());

영숫자 값이 있는 특정 이름 매개 변수를 특정 길이 제한까지 제한된 특정 특수 문자로 교체하는 것과 같이 매우 좁고 구체적인 사용 사례가 있는 경우 다음과 같은 방법을 시도할 수 있습니다.

urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue);

예:

let urlValue = 'www.example.com?a=b&src=test-value&p=q';
const newValue = 'sucess';
console.log(urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue));
// output - www.example.com?a=b&src=sucess&p=q

URL 매개 변수를 대체할 수 있는 최상의 솔루션이 있습니다.

다음 기능은 다음 URL에서 룸 값을 3으로 바꿉니다.

http://example.com/property/ ?min=50000&max=60000&room=1&property_type=House

var newurl = replaceUrlParam('room','3');
history.pushState(null, null, newurl);

function replaceUrlParam(paramName, paramValue){
    var url = window.location.href;

    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;
}

산출량

http://example.com/property/ ?min=50000&max=60000&room=3&property_type=House

매개 변수 편집 URLSearchParams 개체의 설정 방법은 매개 변수의 새 값을 설정합니다.

새 값을 설정한 후 toString() 메서드를 사용하여 새 쿼리 문자열을 얻을 수 있습니다.이 쿼리 문자열은 URL 개체의 검색 속성의 새 값으로 설정할 수 있습니다.

그런 다음 URL 개체의 toString() 메서드를 사용하여 최종 새 URL을 검색할 수 있습니다.


var query_string = url.search;

var search_params = new URLSearchParams(query_string); 

// 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);

출처 - https://usefulangle.com/post/81/javascript-change-url-parameters

UpdateE: http://jsfiddle.net/wesbos/KH25r/1/ 에서 사용자에게 적합한 기능을 제공합니다.

function swapOutSource(url, newSource) {
    params = url.split('&');
    var src = params[0].split('=');
    params.shift();
    src[1] = newSource;
    var newUrl = ( src.join('=') + params.join('&')); 
    return newUrl; 
}

그럼 덤벼봐요!

var newUrl = swapOutSource("http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100","http://link/to/new.jpg");


console.log(newUrl);

자세히 살펴보면 URL에 대한 두 가지 놀라운 점을 볼 수 있습니다. (1) URL은 간단해 보이지만 세부 사항과 코너 케이스는 실제로 어렵습니다. (2) 놀랍게도 자바스크립트는 URL을 사용하는 것을 더 쉽게 할 수 있는 완전한 API를 제공하지 않습니다.본격적인 도서관은 사람들이 직접 바퀴를 다시 발명하거나 누군가의 영리하지만 가능성이 높은 버그 정규식 코드 스니펫을 복사하는 것을 피하기 위한 것이라고 생각합니다.URI.js(http://medialize.github.io/URI.js/) 를 사용해 보십시오.

다음과 같은 방법을 사용합니다.

  • 기록의 URL을 바꿉니다.
  • 제거된 매개 변수의 값을 반환합니다.

    function getUrlParameterAndRemoveParameter(paramName) {
        var url = window.location.origin + window.location.pathname;
        var s = window.location.search.substring(1);
        var pArray = (s == "" ? [] : s.split('&'));
    
        var paramValue = null;
        var pArrayNew = [];
        for (var i = 0; i < pArray.length; i++) {
            var pName = pArray[i].split('=');
            if (pName[0] === paramName) {
                paramValue = pName[1] === undefined ? true : decodeURIComponent(pName[1]);
            }
            else {
                pArrayNew.push(pArray[i]);
            }
        }
    
        url += (pArrayNew.length == 0 ? "" : "?" + pArrayNew.join('&'));
        window.history.replaceState(window.history.state, document.title, url);
    
        return paramValue;
    }
    

파라미터를 자동으로 삭제하는 기능이 누락되었기 때문에 2020년 답변:

제가 좋아하는 답변 https://stackoverflow.com/a/20420424/6284674 을 기반으로 합니다: 저는 다음과 같은 기능을 결합했습니다.

  • 값이 다음과 같은 경우 URL 매개 변수를 자동으로 삭제합니다.null또는''답변 https://stackoverflow.com/a/25214672/6284674 을 기반으로 합니다.

  • 선택적으로 window.location bar에서 직접 업데이트된 URL을 푸시합니다.

  • 정규식만 사용하고 URL 검색 매개 변수는 사용하지 않으므로 IE 지원

JS Fiddle: https://jsfiddle.net/MickV/zxc3b47u/


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

// Orginal URL (default jsfiddle console URL)
//https://fiddle.jshell.net/_display/?editor_console=true

console.log(replaceUrlParam(window.location.href,'a','2'));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=2

console.log(replaceUrlParam(window.location.href,'a',''));   
//https://fiddle.jshell.net/_display/?editor_console=true

console.log(replaceUrlParam(window.location.href,'a',3));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=3

console.log(replaceUrlParam(window.location.href,'a', null));   
//https://fiddle.jshell.net/_display/?editor_console=true&

//Optionally also update the replaced URL in the window location bar
//Note: This does not work in JSfiddle, but it does in a normal browser
function pushUrl(url){
    window.history.pushState("", "", replaceUrlParam(window.location.href,'a','2'));   
}


pushUrl(replaceUrlParam(window.location.href,'a','2'));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=2

pushUrl(replaceUrlParam(window.location.href,'a',''));   
//https://fiddle.jshell.net/_display/?editor_console=true

pushUrl(replaceUrlParam(window.location.href,'a',3));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=3

pushUrl(replaceUrlParam(window.location.href,'a', null));   
//https://fiddle.jshell.net/_display/?editor_console=true&

@stenix 외에도, 이것은 저에게 완벽하게 효과가 있었습니다.

 url =  window.location.href;
    paramName = 'myparam';
        paramValue = $(this).val();
        var pattern = new RegExp('('+paramName+'=).*?(&|$)') 
        var newUrl = url.replace(pattern,'$1' + paramValue + '$2');
        var n=url.indexOf(paramName);
        alert(n)
        if(n == -1){
            newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
        }
        window.location.href = newUrl;

여기서 "url" 변수를 저장할 필요는 없습니다. 현재 URL로 바꾸기만 하면 됩니다.

다음과 같은 것은 어떻습니까?

<script>
function changeQueryVariable(keyString, replaceString) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    var replaced = false;
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == keyString) {
            vars[i] = pair[0] + "="+ replaceString;
            replaced = true;
        }
    }
    if (!replaced) vars.push(keyString + "=" + replaceString);
    return vars.join("&");
}
</script>

이것을 먹어보세요.

var updateQueryStringParam = function (key, value) {

    var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
        urlQueryString = document.location.search,
        newParam = key + '=' + value,
        params = '?' + newParam;

    // If the "search" string exists, then build params from it
    if (urlQueryString) {
        var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
        var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');

        if( typeof value == 'undefined' || value == null || value == '' ) { // Remove param if value is empty
            params = urlQueryString.replace(removeRegex, "$1");
            params = params.replace( /[&;]$/, "" );

        } else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
            params = urlQueryString.replace(updateRegex, "$1" + newParam);

        } else { // Otherwise, add it to end of query string
            params = urlQueryString + '&' + newParam;
        }
    }

    // no parameter was set so we don't need the question mark
    params = params == '?' ? '' : params;

    window.history.replaceState({}, "", baseUrl + params);
};

Regex가 없는 솔루션, 눈에 조금 더 편안함, 내가 찾던 솔루션.

이것은 포트, 해시 매개 변수 등을 지원합니다.

브라우저 특성 요소를 파서로 사용합니다.

function setUrlParameters(url, parameters) {
    var parser = document.createElement('a');
    parser.href = url;

    url = "";

    if (parser.protocol) {
        url += parser.protocol + "//";
    }

    if (parser.host) {
        url += parser.host;
    }

    if (parser.pathname) {
        url += parser.pathname;
    }

    var queryParts = {};

    if (parser.search) {
        var search = parser.search.substring(1);

        var searchParts = search.split("&");
        for (var i = 0; i < searchParts.length; i++) {
            var searchPart = searchParts[i];

            var whitespaceIndex = searchPart.indexOf("=");

            if (whitespaceIndex !== -1) {
                var key = searchPart.substring(0, whitespaceIndex);
                var value = searchPart.substring(whitespaceIndex + 1);

                queryParts[key] = value;
            } else {
                queryParts[searchPart] = false;
            }
        }
    }

    var parameterKeys = Object.keys(parameters);

    for (var i = 0; i < parameterKeys.length; i++) {
        var parameterKey = parameterKeys[i];

        queryParts[parameterKey] = parameters[parameterKey];
    }


    var queryPartKeys = Object.keys(queryParts);

    var query = "";

    for (var i = 0; i < queryPartKeys.length; i++) {
        if (query.length === 0) {
            query += "?";
        }
        if (query.length > 1) {
            query += "&";
        }

        var queryPartKey = queryPartKeys[i];

        query += queryPartKey;

        if (queryParts[queryPartKey]) {
            query += "=";

            query += queryParts[queryPartKey];
        }
    }

    url += query;

    if (parser.hash) {
        url += parser.hash;
    }

    return url;
}

다음은 url 매개 변수를 paramVal로 대체하는 함수입니다.

function updateURLParameter(url, param, paramVal){
        if(!url.includes('?')){
            return url += '?' + param + '=' + paramVal;
        }else if(!url.includes(param)){
            return url += '&' + param + '=' + paramVal;
        }else {
            let paramStartIndex = url.search(param);
            let paramEndIndex = url.indexOf('&', paramStartIndex);
            if (paramEndIndex == -1){
                paramEndIndex = url.length;
            }
            let brands = url.substring(paramStartIndex, paramEndIndex);
    
            return url.replace(brands, param + '=' + paramVal);
        }
    }

두 가지 기능에 의존하는 더 길지만 더 유연한 답변입니다.첫 번째는 모든 매개 변수가 포함된 키/값 사전을 생성하고, 다른 하나는 대체 자체를 수행합니다.이것은 이전 브라우저에서 작동해야 하며 매개 변수가 없을 때 매개 변수를 만들 수도 있습니다.

var get_all_params=function(url)
{               
    var regexS = /(?<=&|\?)([^=]*=[^&#]*)/;
    var regex = new RegExp( regexS,'g' );
    var results = url.match(regex);
    if(results==null)
    {
        return {};
    }
    else
    {
        returned={};
        for(i=0;i<results.length;i++)
        {
            var tmp=results[i];                
            var regexS2="([^=]+)=([^=]+)";
            var regex2 = new RegExp( regexS2 );
            var results2 = regex2.exec(tmp );                
            returned[results2[1]]=results2[2];
        }
        return returned;
    }   
}

var replace_param=function(url, param, value)
{
    var get_params=get_all_params(url);
    var base_url=url.split("?");
    get_params[param]=value;
    var new_params=Array();
    for(key in get_params)
    {
        new_params.push(key+"="+get_params[key]);
    }
    return base_url[0]+"?"+new_params.join("&");
}

호출 예:

var url ="https://geoserver.xxx.com/geoserver/project?service=WFS&version=1.0.0&request=GetFeature&typename=localities";
url=replace_param(url, "service","WMS");

언급URL : https://stackoverflow.com/questions/7171099/how-to-replace-url-parameter-with-javascript-jquery

반응형