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"--
4
Answers
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)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.You seem to want to format each "piece" (name, password) separately, so I would split the original string by the semicolon before attempting the replacement on each element and re-joining.
.
String.prototype.replace
supports a function as a replacer, that runs on every match:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement
In the replacement string you can use
$&
to refer to the string being replaced.