查找并替换具有已定义值的特殊字符

时间:2017-11-11 09:06:47

标签: javascript react-native

如果字符串中包含/,+,?,-,_,#任何一个字符串,我想分别找到并替换_sls_,_pls_,_wht_,_dsh_,_usc_,_hsh_

示例

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

Mary_land = Mary_usc_land
Mary+land = Mary_pls_land

1 个答案:

答案 0 :(得分: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;
}