Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading