It is necessary to make regular expressions. How to write a template for replacing quotes c 'to' - only those that are inside words?

var text = 'Эту "задачу" "нужн"о сделать" регулярным"и выраже"ниями'; var pattern = '/???/'; var result = text.replace(pattern, "'"); console.log(result); 
  • Text in Russian or any language can be? - Grundy
  • easier probably only in Russian - Valeriy Petukhov

3 answers 3

Since the quotation mark is inside the word, there must be letters to its left and right.

Therefore, for the Russian language, the regular may be /([а-яё])"([а-яё])/g .

Substitution pattern: "$ 1 '$ 2" → take the first and second groups (the letters between which there was a quotation mark) and put a single quote between them:

 var text = 'Эту "задачу" "нужн"о сделать" регулярным"и выраже"ниями'; var pattern = /([а-яё])"([а-яё])/g; var result = text.replace(pattern, "$1'$2"); console.log(result); 

    A solution that will work in all browsers should not contain a backward preview block. In addition, to replace the quotes, which follow each other through one letter, you cannot do without a preview block ahead .

    Therefore, the best solution will be

     var text = 'Эту "задачу" "ну"ж"н"о сделать" регулярным"и выраже"ниями'; var pattern = /([а-яё])"(?=[а-яё])/ig; var result = text.replace(pattern, "$1'"); console.log(result); 

    See the regular expression demo .

    Details

    • ([а-яё]) - Exciting group number 1 (reference to the value of this group from the replacement pattern by using $1 ): the letter of the Russian alphabet
    • " - double quote
    • (?=[а-яё]) - a block of preview ahead, which checks the following condition: immediately after the sign " must be a letter of the Russian alphabet
    • ig - modifiers
      • i - case insensitive enabled
      • g - search for all occurrences enabled

    For browsers and environments that support ECMAScript 2018, you can use the following solution for any language:

     var pattern = /(?<=\p{L})"(?=\p{L})/gu; var result = 'Эту "задачу" "ну"ж"н"о сделать" регулярным"и выраже"ниями'.replace(pattern, "'"); console.log(result); 

    \p{L} finds any letter.

       var text = 'Эту "задачу" "нужн"о сделать" регулярным"и выраже"ниями'; var result = text.replace(/(?<=\S)\"(?=\S)/g, "\'"); console.log(result); 

      • something error code gives - Valeriy Petukhov
      • @ValeriyPetukhov, what error? Check here by clicking on Выполнить код - Let's say Pie
      • This gives {"message": "SyntaxError: invalid regexp group", "filename": " stacksnippets.net/js ", "lineno": 14, "colno": 26} - Valeriy Petukhov
      • @ValeriyPetukhov, which browser are you in? - Let's say Pie
      • firefox browser - Valeriy Petukhov