Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    });
});
like image 560
Zach Nicodemous Avatar asked Sep 10 '25 05:09

Zach Nicodemous


2 Answers

var url = /* whatever */;

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

For example,

> 'foobar+'.replace(/\+$/, '');
  "foobar"
like image 173
Matt Ball Avatar answered Sep 12 '25 19:09

Matt Ball


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();
    });
});
like image 30
Jon Avatar answered Sep 12 '25 19:09

Jon