How do I replace with the '\' character with RegExp?

3

I need the character '\' (Reverse Solidus) to be included with the value of the captured group.

Example:

In the sentence assets / pdf / regulation_demais_ddds_ Hi Mod.pdf , I need the excerpt

  

/ pdf

be replaced by

\/pdf\/

forming the phrase

assets\/pdf\/regulamento_demais_ddds_Oi_Mod.pdf

Regular expression working: link

Example Code:

//Expressão regular aplicada 
(\/(?=pdf|images)pdf|\/images)

//Texto para achar o grupo de substituição
const texto = 'assets/pdf/regulamento_Oi_Mod.pdf assets/images/oi-mod-tela-controle-2x.gif'

 const resultado = texto.replace(/(\/(?=pdf|images)pdf|\/images)/g, '/\\/');//Replace para incluir '\' no valor capturado

The problem is that the character '\' is not recognized.

Code:

//Texto para achar o grupo de substituição
const texto = 'assets/pdf/regulamento_Oi_Mod.pdf assets/images/oi-mod-tela-controle-2x.gif'
          
//Replace para incluir '\' no valor capturado
const resultado = texto.replace(/(\/(?=pdf|images)pdf|\/images)/g, '/\\/');

console.log(resultado)
     
    
asked by anonymous 13.04.2018 / 17:37

4 answers

3

var texto = 'assets/pdf/regulamento_Oi_Mod.pdf assets/images/oi-mod-tela-controle-2x.gif';

var mapObj = {
   "/pdf/":"\/pdf\/",
   "/images/":"\/images\/"
};

var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
texto = texto.replace(re, function(matched){
  return mapObj[matched];
});

console.log(texto);
  

So I think it's easier to include more occurrences.

Simply add more occurrences to var mapObj

Example:

var texto = 'assets/pdf/regulamento_Oi_Mod.pdf assets/images/blabla /mais ocorrencias/oi-mod-tela-controle-2x.gif';

 var mapObj = {
   "/pdf/":"\/pdf\/",
   "/images/":"\/images\/",
   "/mais ocorrencias/":"\/mais ocorrencias\/"
};

var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
texto = texto.replace(re, function(matched){
  return mapObj[matched];
});

console.log(texto);
    
13.04.2018 / 19:59
2

You need to escape the backslashes in replace with another backslash:

'\$1\'
 ↑   ↑
barras invertidas de escape

//Texto para achar o grupo de substituição
const texto = 'assets/pdf/regulamento_Oi_Mod.pdf assets/images/oi-mod-tela-controle-2x.gif'
          
//Replace para incluir '\' no valor capturado
const resultado = texto.replace(/(\/(?=pdf|images)pdf|\/images)/g, '\$1\');

console.log(resultado)
    
13.04.2018 / 18:56
1

Hello, to include the character "\" just use the replace method of the String object, as follows:

var texto = 'assets/pdf/regulamento_Oi_Mod.pdf assets/images/oi-mod-tela-controle-2x.gif';
texto = texto.replace(/\//g, '\/');
console.log(texto);

The above code will replace every occurrence of the characters " / " with " \/ ".

    
13.04.2018 / 18:46
-1
var texto = "assets/pdf/regulamento_Oi_Mod.pdf assets/images/oi-mod-tela-controle-2x.gif";
texto.replace(/\/((?=pdf|images)pdf|images)\//g, "\/$1\/")
console.log(texto);
    
13.04.2018 / 20:15