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

问题描述 投票:17回答:6

这是现有问题的延续。 Javascript - Goto URL based on Drop Down Selections (continued!)

我使用下拉选项允许我的用户构建一个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();
    });
});
javascript string
6个回答
26
投票
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();
    });
});

27
投票
var url = /* whatever */;

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

例如,

> 'foobar+'.replace(/\+$/, '');
  "foobar"

-1
投票
<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>

-1
投票
$(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();
    });
});

看起来更容易。


-1
投票

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

-1
投票

使用str.endsWith("str")找到了另一种解决方案

var str = "Hello this is test+";
if(str.endsWith("+")) {
  str = str.slice(0,-1);
  console.log(str)
}
else {
  console.log(str);
}
© www.soinside.com 2019 - 2024. All rights reserved.