2017-11-11 67 views
0

我想查找和替換,如果一個字符串包含/,+,?,-,_,#任何這些分別爲_sls_,_pls_,_wht_,_dsh_,_usc_,_hsh_這個。查找和替換特定字符與定義值

'_sls_'=>'/','_pls_'=>'+','_wht_'=>'?','_dsh_'=>'-','_usc_'=>'_','_hsh_'=>'#' 

Mary_land = Mary_usc_land 
Mary+land = Mary_pls_land 
+0

https://jsfiddle.net/ f5snutvu/ – Andreas

回答

1

寫所有你想要的字符會被替換成一個函數,並調用它

var string1 = "Mary_land"; 
 
var string2 = "Mary+lang"; 
 
var string3 = "Mary#lang"; 
 
var string4 = "Mary-lang"; 
 
var string5 = "Mary/lang?Maryland"; 
 

 
console.log(normalize(string1)); 
 
console.log(normalize(string2)); 
 
console.log(normalize(string3)); 
 
console.log(normalize(string4)); 
 
console.log(normalize(string5)); 
 

 
function normalize(str){ 
 
    str = str.replace(/_/g,"_usc_"); 
 
    str = str.replace(/\+/g,"_pls_"); 
 
    str = str.replace(/\//g,"_sls_"); 
 
    str = str.replace(/#/g,"_hsh_"); 
 
    str = str.replace(/-/g,"_dsh_"); 
 
    str = str.replace(/\?/g,"_wht_"); 
 
    return str; 
 
}

+0

'/''?它變成了評論。 – Balasubramanian

+1

使用反斜槓轉義特殊字符以使javascript將它們視爲常規字符。過期的帖子。 – Nagaraju