简体   繁体   中英

Extract string from img src attribute?

How could i take fontsize, fonttext and fonttype value from following img src

<img 
  src="bin/contenthandler.php?fontsize=36&fonttext=apple&fonttype=fonts/FOO.ttf"
  class="selected content resizable">

I think it can be done with regular expressions but I am bad with them.

Doing it with the location object would be ideal, avoids all the troublesome regex. Borrowed from: Parse URL with jquery/ javascript? and 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'));  

This will return an object with all the variables of the query.
jsFiddle Demo

Despite the other two answers, here is an alternative,

$('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 :) 
});

Another alternative is by using the URI library.

I have used this numerous times and you get exactly what you want, and get everything to do with URI/URL manipulations.

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)
});

here are some examples...

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

more information about how to use ... click here http://medialize.github.io/URI.js/docs.html#accessors-search

This will get you the value 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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM