2016-09-26 85 views
0

我的字符串有兩種flavours-正則表達式追加字符的字符串

var a = /aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo 

var a = /aid/f82eb514073124cd10d468b74eee5663#/propertyinfo 

我想援助後到來的內容追加/和前?或#與「 - 測試」。在上述任何一種情況下,結果將是f82eb514073124cd10d468b74eee5663測試

因此

a = /aid/f82eb514073124cd10d468b74eee5663-test#/propertyinfo 

a = = /aid/f82eb514073124cd10d468b74eee5663-test?sg=1#/propertyinfo 
+0

你有什麼迄今所做? – Oluwafemi

+0

[JavaScript - 獲取URL路徑的部分](http://stackoverflow.com/a/6944772/1115360)可能對您有用。 –

回答

0

好像你正在尋找的東西像this

正則表達式/\/aid\/[0-9A-F]*/i和替換表達式$0-test

JavaScript與簡單的正則表達式滑稽動作有點不同,所以在這裏,

var a = "/aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo"; 
 
alert(a.replace(/(\/aid\/[0-9A-F]*)/i, "$1-test"));

0

給你的例子我想這串/aid/後是某種MD5哈希

這應該爲你工作:

'/aid/f82eb514073124cd10d468b74eee5663#/propertyinfo'.replace(new RegExp('/aid/([a-f0-9]{32})'), '$1-test'); 

,如果你不想成爲長度的具體細節,你可以試試以下內容:

'/aid/f82eb514073124cd10d468b74eee5663#/propertyinfo'.replace(new RegExp('/aid/([a-f0-9]+)'), '$1-test'); 
0

簡單的解決方案使用String.replace功能:

var a = '/aid/f82eb514073124cd10d468b74eee5663sg=1#/propertyinfo', 
    result = a.replace(/aid\/([^?#]+)(?=\?|#)/, "aid/$1-test"); 

console.log(result); // /aid/f82eb514073124cd10d468b74eee5663-test?sg=1#/propertyinfo 
0

我建議直接更換#?所以正則表達式是好的和簡單。 :)

var a = "/aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo"; 
 
var b = "/aid/f82eb514073124cd10d468b74eee5663#/propertyinfo"; 
 

 
console.log(a.replace(/([\?#])/,"-test$1")); 
 
console.log(b.replace(/([\?#])/,"-test$1"));

0
var a = '/aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo'; 

a.replace(/(\/aid\/.+)(\?sg=1)(#\/propertyinfo)/,function(text,c,d,e){ 
    return c+'-test'+e; 
}) 
//Output: "/aid/f82eb514073124cd10d468b74eee5663-test#/propertyinfo" 

a.replace(/(\/aid\/.+)(\?sg=1#\/propertyinfo)/,function(text,c,d){ 
    return c+'-test'+d; 
}); 
//Output: "/aid/f82eb514073124cd10d468b74eee5663-test?sg=1#/propertyinfo"