Link to home
Start Free TrialLog in
Avatar of aguisa
aguisaFlag for Costa Rica

asked on

javascript replace multiple letters

Hi. In order to pass parameters in AJAX, when calling function from js file, special characters like /  ' '(space)  ,  #  , ... they have to be encoded.

I use

codigo = codigo.toUpperCase().replace(/[ ]/g, "_").replace(/[#]/g, "NN").replace(/[/]/g, "ZZZZZZZ")

to make these replacements:

(space) ==> _
# ==> "NN"
/ ==> >"ZZZZZZZ"

I have other procedure I get these names as IDS, so I need to decode these values back, but for example, I use this to decode it:

xcodss = xcods.substring(0,nlen).replace(/["NN"]/g,"#").replace(/[_]/g, " ").replace(/["ZZZZZZZ"]/g, "/");
       
but where I have "Z" , i get / in return
  where I would be expecting only one / if I had 7 Zs (ZZZZZZZ)

for example, if I have "N", then I get #
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Avatar of aguisa

ASKER

ok, the reason is that I'm using the code of an item as the ID of the javascript object.

for example, an Item can have the code:    "#10", so I assign the alias: NN10, and name the object representing this item on the ID='NN10'
so, now in Javascript I can do things like:

$("#NN10").val(...)

The thing is that if I didn't do the replacement, then in Javascript, I would have things like:

$("##10").val(....) which makes some errors, also lets say another code:   "1034 12V"

note the space, now back in JS
, things like  

$("#1034 12V").html(...) would also cause errors, contrary to

$("#1034_12V").html(...)

I appreciate the very good first recommendation, but its falls from being the best approach in my case, lets say I use it, then again, in JS things like (for the item with code= "#10", i.e.)
 
$("#%2310).html(...) Js dont like.

please correct me. thanks
When you escape special characters, the server receive them unescaped. So when you get the characters back in the browser you get them in the original format (unescaped)
ASKER CERTIFIED SOLUTION
Avatar of TRW-Consulting
TRW-Consulting
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial