1. 程式人生 > 其它 >【NodeJS】替換模糊查詢字元裡包含的正則關鍵字

【NodeJS】替換模糊查詢字元裡包含的正則關鍵字

  • 問題:正則匹配時字串中包含了一些特殊字元,導致查詢失敗
    例如,下面的字元包含了( 和 ),這在正則中屬於特殊字元

    (-)-magnocurarine
    

    正則中的特殊字元如下圖

  • 思路:
    1、對映查詢字串的索引位置和對應位置的字元

    Object {0: "\\(", 1: "-", 2: "\\)", 3: "-", 4: "m", 5: "a", 6: "g", 7: "n", 8: "o", 9: "c", 10: "u", 11: "r", …}
    

    2、標記出特殊字元所在的索引位置和字元資訊
    3、在查詢字元中匹配出特殊字元

    const param = "(-)-magnocurarine";
    const key_word = ['$','(',')','*', '+','.','[','?','\\','^','{','}','|' ]
    
    let str_index = 0;
    let str_map_dict={}
    let conflict_map_dict = {}
    for(let p of param){
    	Object.assign(str_map_dict,{[str_index]:p})
    	for(let key of key_word){
    	 if(p == key){
    	   Object.assign(conflict_map_dict,{[str_index]:"\\"+key})
    	}
    	}
    	++str_index;
    }
    
    for(let key of Object.keys(conflict_map_dict)){
    	str_map_dict[key] = conflict_map_dict[key]
    }
    
    new_str= ""
    for(let v of Object.values(str_map_dict)){
    	new_str+=v
    }
    
    
    console.log(new_str)
    
    
    • 返回的結果
    "\\(-\\)-magnocurarine"