0

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?

2
  • 1. This looks like Plone, which already depends on jQuery. Why not use $.query.get? Commented 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. Commented Jun 19, 2011 at 17:46

3 Answers 3

1
str.replace(/SearchableText=[^&]*/, 'SearchableText=' + newWord)
Sign up to request clarification or add additional context in comments.

Comments

1

The \S+ and \S* in your regex match all non-whitespace characters.

You probably want to remove them and the anchors.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.