I have the following:
<a title="Home" href="#">Home test test</a>
I can use a.html() to get me "Home test test" but what I need is just the first word "Home". Is there an easy way that I can do this with jQuery?
I have the following:
<a title="Home" href="#">Home test test</a>
I can use a.html() to get me "Home test test" but what I need is just the first word "Home". Is there an easy way that I can do this with jQuery?
拆分:(如果您愿意,请进一步阅读)http://www.w3schools.com/jsref/jsref_split.asp
另一个使用匹配的演示 http://jsfiddle.net/LAKqB/(使用匹配)
代码
$.fn.ready(function(){
alert($('a').html().split(' ')[0]);
});
使用匹配 api 的代码
$.fn.ready(function(){
var str = $("a").text().match(/\w+/);
alert(str);
});
split()
在javascript中使用函数。
var str = a.html();
alert(str.split()[0]);
这将只返回“家”;
如果它的字符串,"Home test test"
那么您可以使用 split 并获取该数组中的第一个索引:(a.html().split(' ')[0]
在空间上拆分,因此您将获得一个数组["Home", "test", "test"]
:)