2016-11-28 57 views
2

如何在replace函數中使用動態變量作爲第一個參數?使用變量替換所有出現的特定字符串

我有這樣的代碼,當用戶搜索指定的字符串:

var query = jQuery.trim(jQuery(this).val()).toLowerCase(); 
console.log(query + ' was searched') 
jQuery('.one-reference').each(function() { 
    var jQuerythis = jQuery(this); 
    if (jQuerythis.text().toLowerCase().indexOf(query) === -1) { 
     jQuerythis.fadeOut(); 
    } 
    else { 
     jQuerythis.html(jQuerythis.html().replace(/&/g, '<strong>$&</strong>')); 
     jQuerythis.fadeIn(); 
    } 
}); 

replace(/&/g, '<strong>$&</strong>'))不工作。

我想用<strong>標籤覆蓋所有出現的query

+0

你能創建一個演示問題的小提琴嗎? – Anubhav

+0

難道你不應該搜索'query'而不是'&'嗎? – Stefan

+0

@Stefan它將搜索sting'query'然後...不是變量中的字符串'它會搜索' – Umair

回答

3

當您在html中搜索任意值時,您需要創建一個RegExp對象並將其用於replace

if (jQuerythis.text().toLowerCase().indexOf(query) === -1) { 

    jQuerythis.fadeOut(); 
} else { 
    var queryReg = new RegExp(query, 'g'); 
    jQuerythis.html(jQuerythis.html().replace(queryReg, '<strong>$&</strong>')); 
    jQuerythis.fadeIn(); 
} 

而且首先需要逃跑(\)在您的查詢的變量,在正則表達式特殊含義的任何字符(^$[]+()\/-例如) -

query = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); 

(從MDN

請參閱Regular Expressions at Mozilla Developer Network以獲得有關正則表達式的更深入討論。

+2

請務必提及,如果不正確地轉義,那麼在'query'的部分輸入'+'或'[]'將會混淆正則表達式。 – Stefan

+0

他也可以使用函數來清理字符串'query'如: 'function replaceScapeChar(value){ return value.replace(/([\ [| \] | \ || \(| \)| \)。 | \ * | \ + | \ {| \} | \ $])/ g,「\\ $ 1」) }(也許我沒有寫出所有的scape字符,加上我忘記的:p) –

+1

好點@斯特凡補充說。 –

相關問題