mercredi 28 janvier 2015

In Javscript, 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 querystring) in javascript and transform it into another querystring (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?


Aucun commentaire:

Enregistrer un commentaire