开发者

Parsing valid url from long string with pure js or jquery using regex

I get a longString from object's onclick value

var longString = String(this.onclick);

output like below;

function onclic开发者_C百科k(event) { window.location.href = "index.html?q1=v1&g2=v2"; }

I want parse that like below:

index.html?q1=v1&g2=v2

How can I do this with pure js or jquery which works with all browser?


Here's one way to do it if you don't like regular expressions.

var str = 'function onclick(event) { window.location.href = "index.html?q1=v1&g2=v2"; }';
var idx = str.indexOf('"')+1;
var res = str.substr(idx, str.lastIndexOf('"') - idx );

Try it out: http://jsfiddle.net/Tk8aw/


parseUri is what you are looking for.


The following will extract the first match from any one line function (regardless of the name or spacing):

var input = "function onclick(event) { window.location.href = \"index.html?q1=v1&g2=v2\"; }";
var pattern = /function\s+\w+\(\w*\)\s*{\s*window.location.href\s*=\s*['"]([^'"]*)['"];\s*}/i;
var output = pattern.exec(input);

After this runs, the index.html... part will be in output[1]


is this what you are looking for

var str = 'function onclick(event) { window.location.href = "index.html?q1=v1&g2=v2"; }';
alert( /".+?"/.exec(str) );


You can grab it using a regex like this:

var string = 'function onclick(event) { window.location.href = "index.html?q1=v1&g2=v2"; }';
var url = string.match(/"(.*?)"/)[1];
alert(url); // == index.html?q1=v1&g2=v2, without quotes​​​​​​​​​​

You can try a demo here, be aware that the regex returns an object, to get the actual string you're probably after the second entry, [1] here.


This function doesn't do any parsing, but instead declares its own window.location.href, evals the given code, so the onclick becomes a defined function within the scope of this function, runs it, so our local window.location.href gets updated and then returns it. It assumes the contents of the string are known, safe and similar to what you've already given.

function extractURL(code) {
    var window = { location: { href: '' } };
    eval(code);
    onclick();
    return window.location.href;
}

Example use,

var fn = 'function onclick(event) { window.location.href = "index.html?q1=v1&g2=v2"; }';
extractURL(fn); // "index.html?q1=v1&g2=v2"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜