[英]Remove everything after a certain character
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 "?".我希望 href 仅是/Controller/Action
,所以我想删除“?”之后的所有内容。
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);
}
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);
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如果没有
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(result);
If you also want to keep "?"如果您还想保留“?” and just remove everything after that particular character, you can do:并删除该特定字符之后的所有内容,您可以执行以下操作:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
if you add some json syringified objects, then you need to trim the spaces too... so i add the trim() too.如果你添加一些 json syringified 对象,那么你也需要修剪空间......所以我也添加了 trim()。
let x = "/Controller/Action?id=11112&value=4444";
let result = x.trim().substring(0, x.trim().indexOf('?'));
为我工作:
var first = regexLabelOut.replace(/,.*/g, "");
You can also use the split() method which, to me, is the easiest method for achieving this goal.您还可以使用 split() 方法,对我来说,这是实现此目标的最简单方法。 Ex.:前任。:
let dummyString ="Hello Javascript: This is dummy string" dummyString = dummyString.split(':')[0] console.log(dummyString) // Returns "Hello Javascript"
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.