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


Solution 1:[1]

var url = /* whatever */;

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

For example,

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

Solution 2:[2]

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

Solution 3:[3]

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

Solution 4:[4]

$(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.

Solution 5:[5]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt Ball
Solution 2
Solution 3 dpmattingly
Solution 4 Mfoo
Solution 5 givemesnacks