Need to replace a substring in URL (technically just a string) with javascript. The string like
http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE
or
http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest
means, the word to replace can be either at the most end of the URL or in the middle of it. I am trying to cover these with the following:
var newWord = NEW_SEARCH_TERM;
var str = 'http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest';
var regex = /^\S+SearchableText=(.*)&?\S*$/;
str = str.replace(regex, newWord);
But no matter what I do I get str = NEW_SEARCH_TERM. Moreover the regular expression when I try it in RegExhibit, selects the word to replace and everything that follows it that is not what I want.
How can I write a universal expression to cover both cases and make the correct string be saved in the variable?
-
1. This looks like Plone, which already depends on jQuery. Why not use $.query.get?kojiro– kojiro2011年06月19日 16:29:26 +00:00Commented Jun 19, 2011 at 16:29
-
Yes, it's Plone, kojiro. But I don't want to depend on plugins. Seems like $.query.get is not standard function of jQuery and is provided by Query String Object extension. So, not what I really want.spliter– spliter2011年06月19日 17:46:41 +00:00Commented Jun 19, 2011 at 17:46
3 Answers 3
str.replace(/SearchableText=[^&]*/, 'SearchableText=' + newWord)
Comments
The \S+ and \S* in your regex match all non-whitespace characters.
You probably want to remove them and the anchors.
Comments
http://jsfiddle.net/mplungjan/ZGbsY/
ClyFish did it while I was fiddling
var url1="http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE";
var url2 ="http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest"
var newWord = "foo";
function replaceSearch(str,newWord) {
var regex = /SearchableText=[^&]*/;
return str.replace(regex, "SearchableText="+newWord);
}
document.write(replaceSearch(url1,newWord))
document.write('<hr>');
document.write(replaceSearch(url2,newWord))