簡體   English   中英

Javascript - 如果URL字符串的最后一個字符是“+”,那么刪除它......怎么樣?

[英]Javascript - If Last Character of a URL string is “+” then remove it…How?

這是現有問題的延續。 Javascript - 根據下拉選項轉到URL(續!)

我使用下拉選項允許我的用戶構建一個URL,然后點擊“Go”轉到它。

是否有任何方法可以添加一個額外的功能來檢查URL之前的URL?

我的URL有時包含“+”字符,如果它是URL中的最后一個字符,我需要刪除它。 所以它基本上需要“如果最后一個字符是+,刪除它”

這是我的代碼:

$(window).load(function(){
    $('form').submit(function(e){
        window.location.href = 
            $('#dd0').val() +
            $('#dd1').val()+
            $('#dd2').val()+
            $('#dd3').val();
        e.preventDefault();
    });
});
var url = /* whatever */;

url = url.replace(/\+$/, '');

例如,

> 'foobar+'.replace(/\+$/, '');
  "foobar"
function removeLastPlus (myUrl)
{
    if (myUrl.substring(myUrl.length-1) == "+")
    {
        myUrl = myUrl.substring(0, myUrl.length-1);
    }

    return myUrl;
}

$(window).load(function(){
    $('form').submit(function(e){
        var newUrl = $('#dd0').val() +
            $('#dd1').val()+
            $('#dd2').val()+
            $('#dd3').val();
        newUrl = removeLastPlus(newUrl);
        window.location.href = newUrl;
        e.preventDefault();
    });
});

使用str.endsWith("str")找到另一個解決方案

 var str = "Hello this is test+"; if(str.endsWith("+")) { str = str.slice(0,-1); console.log(str) } else { console.log(str); } 

 function removeLastPlus(str) { if (str.slice(-1) == '+') { return str.slice(0, -1); } return str; } 

<script type="text/javascript">
  function truncate_plus(input_string) {
    if(input_string.substr(input_string.length - 1, 1) == '+') {
      return input_string.substr(0, input_string.length - 1);
    }
    else
    {
      return input_string;
    }
  }
</script>
$(window).load(function(){
    $('form').submit(function(e){
        var newUrl = $('#dd0').val() +
            $('#dd1').val()+
            $('#dd2').val()+
            $('#dd3').val();
        newUrl = newUrl.replace(/\+$/, '');
        window.location.href = newUrl;
        e.preventDefault();
    });
});

看起來更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM