如何将 jquery attr 值转换为字符串对象以将其用作正则表达式?
我想搜索一个字符串变量,如果它包含 jQuery 对象的 attr 值。我已经尝试过:
var txt = "lets go to a.html";
var searchText = new RegExp($("#link").attr("href"));
alert(txt.search(searchText)>=0);
但这总是返回 false。 我确信 $("#link").attr("href") 返回“a.html”作为值。 如果我做错了什么,我也尝试过这个,
var txt = "lets go to a.html";
var searchText = new RegExp("a.html");
alert(txt.search(searchText)>=0);
这次它返回了 true。 我认为 jquery 没有返回字符串对象,我尝试将其转换为这样的字符串:
var txt = "lets go to a.html";
var searchText = new String($("#link").attr("href"));
searchText = new RegExp(searchText);
alert(txt.search(searchText)>=0);
这也返回 false..
当我使用 toString($("#link").attr("href")) 它总是即使 attr 值不是“a.html”也返回 true
任何人都可以帮助我吗? 谢谢。
i want to search a string variable if it contains a jQuery object's attr value. I have tryed this:
var txt = "lets go to a.html";
var searchText = new RegExp($("#link").attr("href"));
alert(txt.search(searchText)>=0);
but this always returns false.
im sure that $("#link").attr("href") returns "a.html" as value.
also i have tried this if i was doing something wrong,
var txt = "lets go to a.html";
var searchText = new RegExp("a.html");
alert(txt.search(searchText)>=0);
this time it has returned true.
i thought jquery was not returning a string object and i have tried to turn it to string like this:
var txt = "lets go to a.html";
var searchText = new String($("#link").attr("href"));
searchText = new RegExp(searchText);
alert(txt.search(searchText)>=0);
this has aslo returned false..
when i used toString($("#link").attr("href")) it always returns true even attr value is not "a.html"
anyone can help me on this?
thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这样做:
Do this:
要从字符串创建正则表达式:
要查看它是否与另一个字符串匹配:
请注意,必须对某些字符进行转义,以便匹配空格:
在您的情况下,您应该反转测试的含义:
它将返回 true if “a.html”在 txt 中。
To create a regular expression from a string:
To see if it matches another string:
Note though that some characters must be escaped, so to match a whitespace:
In your case, you should reverse the sense of the test:
which will return true if 'a.html' is in txt.
根据您在 href 属性中测试的浏览器,当通过 jQuery 查询时,即使您已将其设置为相对 url,也会返回完全限定的 url。
进行测试以确保
$('#link').attr('href')
实际上返回a.html
而不是http://url/a .html
。Depending on what browser you are testing in the href attribute, when queried through jQuery, will return a fully qualified url even tho you have set it to a relative url.
Test to make sure that
$('#link').attr('href')
actually returnsa.html
and nothttp://url/a.html
.好吧,问题已经解决了,我必须对所有花时间解决这个问题的人说声抱歉
问题出在我的 html 上:(
我在 href 属性中放入了一个空字符,如下所示:
我给出的代码都运行良好:)
Okay problem is solved i must say sorry to everyone who spent time to solve this problem
problem was on my html :(
i have putted an emty character inside the href attribute like this:
the codes i have given all are working well :)