Skip to content
Advertisement

In JavaScript, what is the simplest way to insert text into a string?

I have an issue where I need to take a string (which is a query string) in JavaScript and transform it into another query string (to avoid clashes).

The original string I have comes in as:

fieldA=10&fieldB=10&fieldC=10&fieldD=10&arrayfieldA=100&arrayfieldA=200

And I want to take a prefix (in my case it will be something like “slides[0].” and put it in front of all of the items, so I end up with:

slides[0].fieldA=10&slides[0].fieldB=10&slides[0].fieldC=10&slides[0].fieldD=10&slides[0].arrayfieldA=100&slides[0].arrayfieldA=200

In JavaScript, what is the simplest way to transform the first string into the second?

I could use

  • Simple find / “replace()” (.replace(“&”, “&slides[0]”)
  • Convert to array and then spit back to a concatenated string
  • others?

Currently I am doing this:

function EnrichString(startString, prefix) {
    return prefix + startString.replace("&", "&" + prefix);
}

But I wanted to confirm if there are any gotchas with this approach?

Advertisement

Answer

Use:

var queryStringParts = queryString.split('&');
var pairs = queryStringParts.map(function(str) { return str.split('=') })
var rewrittenParts = pairs.map(function(pair){
                          return 'slides[0].' + pair[0] + '=' + pair[1]
                     });
var newQuerystring = rewrittenParts.join('&');

As was pointed out in the comments, in this specific case we could skip the split into pairs step and just do

var queryStringParts = queryString.split('&');
var rewrittenParts = queryStringParts.map(function(part) {
                          return 'slides[0].' + part
                     });
var newQuerystring = rewrittenParts.join('&');
Advertisement