我怎麼能取字號,fonttext和fonttype值從以下IMG SRC
從img src屬性中提取字符串?
<img
src="bin/contenthandler.php?fontsize=36&fonttext=apple&fonttype=fonts/FOO.ttf"
class="selected content resizable">
我認爲它可以使用正則表達式來完成,但我不好他們。
我怎麼能取字號,fonttext和fonttype值從以下IMG SRC
從img src屬性中提取字符串?
<img
src="bin/contenthandler.php?fontsize=36&fonttext=apple&fonttype=fonts/FOO.ttf"
class="selected content resizable">
我認爲它可以使用正則表達式來完成,但我不好他們。
與位置對象做這將是理想,避免了所有令人頭疼的正則表達式。 從借來的: Parse URL with jquery/ javascript? 和 https://developer.mozilla.org/en/window.location
function buildValue(sValue) {
if (/^\s*$/.test(sValue)) { return(null); }
if (/^(true|false)$/i.test(sValue)) { return(sValue.toLowerCase() === "true"); }
if (isFinite(sValue)) { return(parseFloat(sValue)); }
if (isFinite(Date.parse(sValue))) { return(new Date(sValue)); }
return(sValue);
}
function getVars(url) {
var oGetVars = {};
var a = document.createElement('a');
a.href = url;
var iCouple, aCouples = a.search.substr(1).split("&");
for (var iCouplId = 0; iCouplId < aCouples.length; iCouplId++) {
iCouple = aCouples[iCouplId].split("=");
oGetVars[unescape(iCouple[0])] = iCouple.length > 1 ? buildValue(unescape(iCouple[1])) : null;
}
return oGetVars;
}
console.log(getVars('http://google.com?q=123&y=xyz'));
這將返回一個對象與查詢的所有變量。
jsFiddle Demo
這會讓你的價值36
。
var rx = /fontsize=(.*?)&/;
var fontsize = rx.exec('<img src="bin/contenthandler.php?fontsize=36&fonttext=apple&fonttype=fonts/FOO.ttf" class="selected content resizable">')[1];
儘管其他兩個答案,這裏是一個另類,
$('img[src]').each(function (i,n){
var item = $(n).attr('src');
var query = item.split('?');
var items = query.split('&') ;
// so now you get the point, u split each item again by the "=" sign :) this is reusable
// provided you put it on a function, and it can search to return a specific one, with a little imagination :)
});
另一種方法是使用URI庫。
我已經使用了這麼多次,你得到了你想要的,並得到一切與URI/URL操作。
http://medialize.github.io/URI.js/
$('img[src]').each(function (i,n){
var src = $(n).attr('src');
var get_query = URI(src).query()
console.log(get_query)
});
這裏有一些例子......有關如何使用
URI("testme?test").query();// returns: test
URI("testme?a=1&b=2").query(true) // returns: {a: "1", b: "2"}
URI("testme?font_size=15&font_name=arial").query(true).font_size // 15
更多信息...點擊這裏http://medialize.github.io/URI.js/docs.html#accessors-search
迄今爲止最好的答案,並可重複使用:) – Val
感謝您的幫助。 –