从img src属性中提取字符串
Extract string from img src attribute?
如何从以下img src中获取fontsize, fonttext和fonttype值
<img
src="bin/contenthandler.php?fontsize=36&fonttext=apple&fonttype=fonts/FOO.ttf"
class="selected content resizable">
我认为它可以用正则表达式完成,但我不擅长它们。
使用location对象进行此操作是理想的,可以避免所有麻烦的正则表达式。借鉴:解析URL与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演示
除了其他两个答案,这里还有一个选择,
$('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
这将得到值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];
相关文章:
- 使用gulp-angular gettext从JS文件中提取字符串不起作用
- Javascript:如何通过Regexp从属性中提取字符串
- 使用Node/Javascript提取字符串中的所有占位符
- 需要从随机大小的字符串中提取字符串
- 用unicode字符提取字符串中的单词
- 使用java脚本提取字符串
- JavaScript:如何提取字符串中的复杂内容
- 如何删除“;NULL”;使用Javascript从sails.js中的JSON对象中提取字符串
- 当前面的数字或前面字符的组合未知时提取字符串
- 如何根据 javascript 中的两个字符比较从另一个字符串中提取字符串
- 从两边提取字符串和相等数量的字符
- 如何在从 javascript 中的 json 对象中提取字符串时保留转义序列.(字符串实际上是正则表达式模式)
- 使用 javascript 从脚本标记中提取字符串
- 如何根据某些正则表达式模式提取字符串的“部分”
- 检查是否为数字,如果是字母,则在javascript中提取字符串的一部分
- 介绍JS学生使用isNaN(与其他语句结合使用)提取字符串
- 正则表达式后视以提取字符串
- 从另一个url或字符串中提取字符串
- 使用Javascript提取字符串中的数字
- 在javascript中提取字符串中的数字