PDA

View Full Version : Replace function - problem with ? in parameter



kbdkn
09-16-2008, 07:55 PM
Hi - the replace function doesn't care for the leading ? in bold below. Using \ as an escape doesn't help - is there a different escape character, or a way around this? (3.1.0-RC1, Vista Business.)


var str1 = "?careId=";

var str2 = replace(str1,"careId=", "&careId=");
Alert(str2);

var str3 = replace(str2,"?&careId=", "?careId=");
Alert(str3);


Thanks
-Kim

Error message:

Couldn't execute this script! Error on position (6:0) :
Function call replace is not valid : Dangling meta character '?' near index 0
?&careId=
^ (script#6)

DEinspanjer
09-17-2008, 12:02 AM
replace is expecting a regular expression. ? is a special character in regular expressions. A single backslash won't work because you are using double quotes which means that Javascript will attempt to parse the backslash as a escape for a string character (such as \t or \n). You need two backslashes. \\ in a Java or Javascript string means "this is a literal backslash character", then, the literal backslash goes into the regular expression and the regex interprets that as "ignore the special meaning of the next character (e.g. the ?)".

var str3 = replace(str2,"\\?&careId=", "?careId=");

kfd
09-17-2008, 11:36 AM
Thank you!