简体   繁体   English

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

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

This is a continuation from an existing question. 这是现有问题的延续。 Javascript - Goto URL based on Drop Down Selections (continued!) Javascript - 根据下拉选项转到URL(续!)

I am using dropdown selects to allow my users to build a URL and then hit "Go" to goto it. 我使用下拉选项允许我的用户构建一个URL,然后点击“Go”转到它。

Is there any way to add an additional function that checks the URL before going to it? 是否有任何方法可以添加一个额外的功能来检查URL之前的URL?

My URLs sometimes include the "+" character which I need to remove if its the last character in a URL. 我的URL有时包含“+”字符,如果它是URL中的最后一个字符,我需要删除它。 So it basically needs to be "if last character is +, remove it" 所以它基本上需要“如果最后一个字符是+,删除它”

This is my code: 这是我的代码:

$(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(/\+$/, '');

For example, 例如,

> '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();
    });
});

Found another solution using str.endsWith("str") 使用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();
    });
});

Just seems easier. 看起来更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM