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

Zac*_*ous 18 javascript string

这是现有问题的延续. Javascript - 根据下拉选项转到URL(续!)

我使用下拉选项允许我的用户构建一个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();
    });
});
Run Code Online (Sandbox Code Playgroud)

Mat*_*all 28

var url = /* whatever */;

url = url.replace(/\+$/, '');
Run Code Online (Sandbox Code Playgroud)

例如,

> 'foobar+'.replace(/\+$/, '');
  "foobar"
Run Code Online (Sandbox Code Playgroud)


Jon*_*Jon 27

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();
    });
});
Run Code Online (Sandbox Code Playgroud)


Bla*_*mba 5

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

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