开发者

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!)

I am using dropdown selects to allow my users to build a URL and then hit "Go" to goto it.

Is th开发者_JAVA百科ere any way to add an additional function that checks the URL before going to it?

My URLs sometimes include the "+" character which I need to remove if its the last character in a 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")

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

Also Matt Ball's Replace method looks good. I've updated it to handle the case when there are multiple + at the end.

let str = "hello+++++++++";
str = str.replace(/\++$/, '');
console.log(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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜