2017-09-07 42 views
1

工作,我有這樣的替換字符串和它周圍的支架沒有與正則表達式

var str = '[a] is a string with many [a] but only one [b]'; 

一鍵多次出現的字符串,現在我有一個與他們在海峽值的鍵的對象;

var obj = {a:'the a',b:'the b'}; 

我試着像這樣與他們的價值觀取代那些鍵

let output = str; 
for (const key in obj) { 
     output = output.replace(new RegExp('[[' + key + ']]', 'g'), obj[key]); 
    } 

其輸出

[the a is a string with many [the a but only one [the b 

任何機構可以告訴我缺少的是什麼?

編輯

我怎麼能代替@[a](a)the a@[b](b)the b?即

var str = '@[a](a) is a string with many @[a](a) but only one @[b](b)'; 

回答

1

您應該使用此代碼:

var str = '@[a](a) is a string with many @[a](a) but only one @[b](b)'; 
 
var obj = {a:'the a',b:'the b'}; 
 

 
let output = str; 
 
for (const key in obj) { 
 
    output = output.replace(new RegExp('@\\[' + key + '\\]\\(' + key + '\\)', 'g'), obj[key]); 
 
} 
 

 
console.log(output); 
 
//=> "the a is a string with many the a but only one the b"

[必須在Javascript中的正則表達式進行轉義,並使用RegExp當建築工轉義兩次。

+0

你能回答編輯的問題嗎? – ahmadalibaloch

+1

當然,讓我看看。順便說一句,你不需要取消我的答案,要求進一步增強。我總是盡最大努力回答所有問題。 – anubhava

+0

好的,我在等你的答案。 – ahmadalibaloch

1

[[a]]

匹配任一[]a]因爲它解析到

[[a]   # Class, '[' or 'a' 
]    # followed by ']' 

爲了修正它,逃生外托架文字因此它們是文字。

output = output.replace(new RegExp('\\[[' + key + ']\\]', 'g'), obj[key]);

,你甚至可以擺脫內括號之內,因爲只有1次關鍵傳球每個。

output = output.replace(new RegExp('\\[' + key + '\\]', 'g'), obj[key]);

+0

很好的解釋。 – ahmadalibaloch

+0

@ahmadalibaloch - 當心離開文字類括號未逃脫。正則表達式的設計師很久以前就離開了可能是文字的拖車而不必逃脫。當正則表達式變得越來越複雜時,這會是一個壞習慣。 – sln

+0

我剛接到另一個問題,'@ [a](a)'如何用'a'替換它。我不想爲此發佈另一個問題。 – ahmadalibaloch