javascriptjquery

How to replace a quoted string with a modified version of it JQuery/Javascript


I'm looking for a solution to replace all quoted strings in a phrase with the same quoted strings but in a modified version.

This is an example of what I mean:

var str = 'name="benson"; password="1234"';

//Expected output: name=--"benson"--; passowrd=--"1234"--


var str = 'I "love" and I like "programming"';

//Expected output: I --"love"-- and I like --"programming"--
// and so on

Following is my approach, I'm almost there but it seems I'm missing something. I have spent quite some time on it.

var str = 'name="benson"; password="1234"';

var searching = str.match(/".+?"/gi); 

var result = str.replace(/".+?"/gi, "--" + searching + "--");

$( "p" ).html(result);

// out put: name=--"benson","1234"--; password=--"benson","1234"--

Solution

  • The .replace function supports a special syntax where you can tell it to use the matching part when replacing.. (but you need to use capturing groups for this)

    var str = 'name="benson"; password="1234"';
    var result = str.replace(/(".+?")/gi, "--$1--");
    
    $( "p" ).html(result);
    

    In this case, we create a mathcing group for the quoted string you want, and in the replace method we specify with $1 where the matching data of that group should be inserted in the replacement.