用javascript替换子字符串

用javascript替换子字符串,javascript,regex,replace,Javascript,Regex,Replace,需要用javascript替换URL中的子字符串(技术上只是一个字符串)。 弦状 http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE 或 意味着,替换的单词可以位于URL的最末端,也可以位于URL的中间。 我试图用以下内容来说明这些问题: var newWord = NEW_SEARCH_TERM; var str = 'http://blah-blah.c

需要用javascript替换URL中的子字符串(技术上只是一个字符串)。 弦状

http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE

意味着,替换的单词可以位于URL的最末端,也可以位于URL的中间。 我试图用以下内容来说明这些问题:

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);
但无论我做什么,我都会得到str=NEW\u SEARCH\u TERM。此外,当我在RegExhibit中尝试正则表达式时,它会选择要替换的单词,并且后面的所有内容都不是我想要的


如何编写一个通用表达式来覆盖这两种情况,并使正确的字符串保存在变量中?

正则表达式中的
\S+
\S*
匹配所有非空白字符

您可能希望删除它们和锚定。

str.replace(/SearchableText=[^&]*/, 'SearchableText=' + newWord)
克莱菲什是在我摆弄小提琴的时候做的

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))
var url1=”http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE";
变量url2=”http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest"
var newWord=“foo”;
函数替换搜索(str,newWord){
var regex=/SearchableText=[^&]*/;
返回str.replace(regex,“SearchableText=“+newWord”);
}
document.write(replaceSearch(url1,newWord))
文件。写(“
”); document.write(replaceSearch(url2,newWord))
1。这看起来像Plone,它已经依赖于jQuery。为什么不使用$.query.get?是的,是Plone,kojiro。但我不想依赖插件。似乎$.query.get不是jQuery的标准函数,而是由提供的。所以,这不是我真正想要的。
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))