是否有一种方法可以删除某个字符之后的所有内容,或者只是选择该字符之前的所有内容?我从href到?的值,它总是不同数量的字符。

像这样

/Controller/Action?id=11112&value=4444

我想href是/Controller/Action,所以我想删除“?”之后的所有东西。

我现在用这个:

 $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');                
     var url = $(this).attr('href');

     console.log(url);
 }

当前回答

这对我来说非常有效:

var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result =  x.substring(0, remove_after);
alert(result);

其他回答

如果你还想保留"?",并删除该特定字符后面的所有内容,你可以这样做:

var str = "/Controller/Action?id=11112&value=4444",
    stripped = str.substring(0, str.indexOf('?') + '?'.length);

// output: /Controller/Action?

如果你添加了一些json对象,那么你也需要修剪空格…所以我也添加了trim()。

let x = "/Controller/Action?id=11112&value=4444";
let result =  x.trim().substring(0,  x.trim().indexOf('?'));  
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);

样品在这里

我还应该提到本机字符串函数比正则表达式快得多,正则表达式只应该在必要时使用(这不是其中之一)。

更新代码以解释没有'?':

var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);

样品在这里

var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action

如果找到'?’如果没有的话

可能很晚了党:p

你可以使用反向引用$'

$' - Inserts the portion of the string that follows the matched substring.

let str = "/控制器/动作? "id = 11112平均数= 4444” Let output = str.replace(/\?.*/g,"$'") console.log(输出)