skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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.

    const str = 'name="benson"; password="1234"';
    
    const result = [];
    str.split(";").forEach(
      subst => {
        const searching = subst.match(/".+?"/gi);
        result.push(subst.replace(/".+?"/gi, "--" + searching + "--"));
      }
    
    )
    
    
    $("p").html(result.join("; "));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <p></p>

    .

    Login or Signup to reply.
  3. 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

    var str = 'name="benson"; password="1234"';
    
    var result = str.replace(/".+?"/gi, (match) => "--" + match + "--");
    
    $('#out').append(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div id="out"></div>
    Login or Signup to reply.
  4. In the replacement string you can use $& to refer to the string being replaced.

    var str = 'name="benson"; password="1234"';
    var result = str.replace(/".+?"/gi, "--$&--");
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search