当前位置: 动力学知识库 > 问答 > 编程问答 >

Replace characters before question mark of current URL with javascript bookmarklet

问题描述:

Is there a way to replace all characters before the question mark in a URL via a javascript bookmarklet?

I found a way to replace parts in the URL but only if the current url is the same all the time.

But my url is different with alot of subpages so i need to isolate everything before the question Mark

Example 1:

http://www.marktplaats.nl/z.html?query=bucky&searchOnTitleAndDescription=true&categoryId=356&postcode=

Should be changed to:

http://www.rss2search.nl/marktplaats/zoek.php?query=bucky&searchOnTitleAndDescription=true&categoryId=356&postcode=

Can i change it by selecting everything before the question mark?

网友答案:

Convert your URL into an array:

var arr = 'http://www.marktplaats.nl/z.html?query=buck...'.split('?');

Join the new URL text and the second element of arr together:

var text = 'http://www.rss2search.nl/marktplaats/zoek.php';
var out = [text, arr[1]].join('?');

DEMO

网友答案:

Yes, it can be done like this...

var url = "http://www.rss2search.nl/marktplaats/zoek.php";
location.href = url + location.href.substr(location.href.indexOf("?"));

For your bookmarklet, add this as the url...

javascript:(function(){location.href="http://www.rss2search.nl/marktplaats/zoek.php"+location.href.substr(location.href.indexOf("?"));return false;})()
网友答案:

You can try below code:

// This regex pattern will take whatever string before question mark
var re = /(.+)\?/; 

var str = 'http://www.marktplaats.nl/z.html?query=bucky&searchOnTitleAndDescription=true&categoryId=356&postcode=';

// And then replace with this string
var subst = 'http://www.rss2search.nl/marktplaats/zoek.php'; 

var result = str.replace(re, subst);
分享给朋友:
您可能感兴趣的文章:
随机阅读: