I have this string: #test
or #test?params=something
我有这个字符串:#test或#test?params = something
var regExp = /(^.*)?\?/;
var matches = regExp.exec($(this).data('target'));
var target = matches[1];
console.log(target);
I always need to get only #test.
The function I pasted returns an error if no question mark is found. The goal is to always return #test
whether there are additional params or not. How do I make a regex that returns this?
我总是只需要获得#test。如果没有找到问号,我粘贴的函数会返回错误。目标是始终返回#test是否有其他参数。如何制作一个返回此值的正则表达式?
5 个解决方案
#1
4
Is that string direct from the current page's URL?
该字符串是否直接来自当前页面的URL?
If so, you can simply use:
如果是这样,您可以简单地使用:
window.location.hash.split('?')[0]
If you're visiting http://example.com/#test?params=something, the above code will return "#test".
如果您访问http://example.com/#test?params=something,上面的代码将返回“#test”。
Tests
example.com/#test -> "#test"
example.com/#test?params=something -> "#test"
example.com/foo#test -> "#test"
example.com -> ""
#3
1
You can use:
您可以使用:
var regExp = /^([^?]+)/;
This will always return string before first ?
whether or not ?
is present in input.
这将始终在第一个之前返回字符串?是否?存在于输入中。
RegEx Demo
#4
1
Simple alternative:
hash = str.substr(0, (str + "?").indexOf("?"));
#5
#1
4
Is that string direct from the current page's URL?
该字符串是否直接来自当前页面的URL?
If so, you can simply use:
如果是这样,您可以简单地使用:
window.location.hash.split('?')[0]
If you're visiting http://example.com/#test?params=something, the above code will return "#test".
如果您访问http://example.com/#test?params=something,上面的代码将返回“#test”。
Tests
example.com/#test -> "#test"
example.com/#test?params=something -> "#test"
example.com/foo#test -> "#test"
example.com -> ""
#2
#3
1
You can use:
您可以使用:
var regExp = /^([^?]+)/;
This will always return string before first ?
whether or not ?
is present in input.
这将始终在第一个之前返回字符串?是否?存在于输入中。
RegEx Demo
#4
1
Simple alternative:
hash = str.substr(0, (str + "?").indexOf("?"));