Javascript正则表达式在问号之前获取字符串(如果存在)

时间:2021-05-24 22:26:31

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                           -> ""

#2


2  

^(.*?)(?=\?|$)

You can try this.See demo.

你可以试试这个。看看演示。

https://regex101.com/r/vN3sH3/25

#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


0  

Either I'm missing something or simply:

要么我错过了什么,要么只是:

 ^#\w+

Seems to do the job for both(this and this) scenarios

似乎为这个(这个和这个)场景做了工作

#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


2  

^(.*?)(?=\?|$)

You can try this.See demo.

你可以试试这个。看看演示。

https://regex101.com/r/vN3sH3/25

#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


0  

Either I'm missing something or simply:

要么我错过了什么,要么只是:

 ^#\w+

Seems to do the job for both(this and this) scenarios

似乎为这个(这个和这个)场景做了工作