2011-06-19 125 views
0

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

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

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

装置的字符串,替换的单词可以是在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); 

但无论我做什么,我得到海峡= NEW_SEARCH_TERM。此外,正则表达式,当我在RegExhibit中尝试它时,选择要替换的单词以及它后面的所有内容,这不是我想要的。

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

+0

1.这看起来像Plone的,它已经依赖于jQuery的。为什么不使用$ .query.get? – kojiro

+0

是的,这是Plone,kojiro。但我不想依赖插件。看起来像$ .query.get不是jQuery的标准功能,并且由[查询字符串对象扩展](http://plugins.jquery.com/project/query-object)提供。所以,不是我真正想要的。 – spliter

回答

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

谢谢,这真像一种魅力 – spliter

1

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

你可能想要删除它们和锚点。

0

http://jsfiddle.net/mplungjan/ZGbsY/

ClyFish做到了,而我是胡乱

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