2017-09-18 9 views
0

*?は、単語の先頭とコロンの間にと表示される場合、文字列にエスケープしようとしています。たとえば正規表現を使用して単語の先頭とコロンの間に特殊文字をエスケープする

Input: creator*:Joh*n url:*google* 
Output: creator\*:Joh*n url:*google* 

そして、ここでは私のJavaScriptコードです:

var str = 'creator*:Joh*n url:*google*'; 
var regex = /\b([\w.]*)([\*\?]+)([\w.]*:)/g; 
str = str.replace(regex, "$1\\$2$3"); 
alert(str); 

それは私が期待通りに動作します。ただし、2つの問題があります。

問題1: *が単語の先頭にある場合は機能しません。

Input: *creator:Joh*n url:*google* 
Output: *creator:Joh*n url:*google* 
Expected result: \*creator:Joh*n url:*google* 

問題2:つ以上の*がある場合、それは動作しません。

Input: cre*ato*r:Joh*n url:*google* 
Output: cre*ato\*r:Joh*n url:*google* 
Expected result: cre\*ato\*r:Joh*n url:*google* 

私のパターンには何が問題なのですか?ご協力いただきありがとうございます。あなたは

function replace(str){ 
 
    return str.replace(/([*?])(?=[^\s]*:)/g, '\\$1'); 
 
} 
 

 

 
console.log(replace('creator*:John url:*google*')); 
 
console.log(replace('*creator:John url:*google*')); 
 
console.log(replace('cre*ato*r:John url:*google*')); 
 
console.log(replace('creator*:John url:*google* author:Alice'));

次のようにこれを行うことができます

答えて

3
+0

が、それはタイプミスだったそうではない/ – epascarello

+0

\されなければならない参照の答えをあなたのための – marvel308

+0

感謝を編集しましたしかし、私たちが '* * n 'に変えれば、私は欲しくない' *'もエスケープするでしょう。私の更新されたコードを見てください:) – AnhTriet

関連する問題