Javascript 删除某个字符后的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5631384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove everything after a certain character
提问by Dejan.S
Is there a way to remove everything after a certain character or just choose everything up to that character? I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.
有没有办法删除某个角色之后的所有内容,或者只选择该角色之前的所有内容?我从 href 到“?”获取值,并且它总是会是不同数量的字符。
Like this
像这样
/Controller/Action?id=11112&value=4444
I want the href to be /Controller/Action
only, so I want to remove everything after the "?".
我希望/Controller/Action
只有href ,所以我想删除“?”之后的所有内容。
I'm using this now:
我现在正在使用这个:
$('.Delete').click(function (e) {
e.preventDefault();
var id = $(this).parents('tr:first').attr('id');
var url = $(this).attr('href');
console.log(url);
}
回答by Demian Brecht
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).
我还应该提到本机字符串函数比正则表达式快得多,正则表达式应该只在必要时使用(这不是这些情况之一)。
Updated code to account for no '?':
更新代码以考虑没有“?”:
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
回答by kapa
回答by James Kyburz
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
This will work if it finds a '?' and if it doesn't
如果找到“?”,这将起作用 如果没有
回答by patad
If you also want to keep "?" and just remove everything afterthat particular character, you can do:
如果您还想保留“?” 并删除该特定字符之后的所有内容,您可以执行以下操作:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
回答by Code Maniac
回答by Samina Samina
It works for me very nicely:
它非常适合我:
var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result = x.substring(0, remove_after);
alert(x);
回答by Samina Samina
Worked for me:
为我工作:
var first = regexLabelOut.replace(/,.*/g, "");
回答by Imran
It can easly be done using JavaScript for reference see link JS String
它可以很容易地使用 JavaScript 完成以供参考,请参阅链接 JS String
EDIT it can easly done as. ;)
编辑它可以很容易地完成。;)
var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);