Dej*_*n.S 252 javascript jquery
有没有办法删除某个角色后的所有内容,或者只选择该角色的所有内容?我从href获得了值,直到"?",它总是会有不同数量的字符.
像这样
/Controller/Action?id=11112&value=4444
Run Code Online (Sandbox Code Playgroud)
我希望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);
}
Run Code Online (Sandbox Code Playgroud)
Dem*_*cht 426
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
Run Code Online (Sandbox Code Playgroud)
编辑:
我还要提一下,本机字符串函数比正则表达式快得多,正则表达式应该只在必要时使用(这不是其中一种情况).
第二编辑:
更新了代码以解释没有'?':
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
Run Code Online (Sandbox Code Playgroud)
kap*_*apa 254
您也可以使用该split()功能.这似乎是我脑海中最简单的:).
url.split('?')[0]
Run Code Online (Sandbox Code Playgroud)
一个优点是即使?字符串中没有,此方法也会起作用- 它将返回整个字符串.
Jam*_*urz 18
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
Run Code Online (Sandbox Code Playgroud)
如果找到'?',这将有效 如果没有
Cod*_*iac 12
聚会可能会很晚:p
您可以使用反向引用$'
$' - Inserts the portion of the string that follows the matched substring.
Run Code Online (Sandbox Code Playgroud)
$' - Inserts the portion of the string that follows the matched substring.
Run Code Online (Sandbox Code Playgroud)
小智 7
您还可以使用split()对我来说是实现此目标的最简单方法的方法。
例如:
let dummyString ="Hello Javascript: This is dummy string"
dummyString = dummyString.split(':')[0]
console.log(dummyString)
// Returns "Hello Javascript"Run Code Online (Sandbox Code Playgroud)
小智 6
它非常适合我:
var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result = x.substring(0, remove_after);
alert(result);
Run Code Online (Sandbox Code Playgroud)
如果您还想保留“?” 然后删除该特定字符之后的所有内容,您可以执行以下操作:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
Run Code Online (Sandbox Code Playgroud)