spliter
spliter

Reputation: 12599

Replace a substring with javascript

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?

Upvotes: 0

Views: 374

Answers (3)

mplungjan
mplungjan

Reputation: 178384

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

Upvotes: 0

clyfish
clyfish

Reputation: 10470

str.replace(/SearchableText=[^&]*/, 'SearchableText=' + newWord)

Upvotes: 1

SLaks
SLaks

Reputation: 888107

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

You probably want to remove them and the anchors.

Upvotes: 1

Related Questions