Switching CHARs Position on STRINGS!! URGENT PLEAS

Thread: Switching CHARs Position on STRINGS!! URGENT PLEAS

1. Eduard Guest

Switching CHARs Position on STRINGS!! URGENT PLEAS

Hey, I would like to know how to make a function<BR>like that :<BR><BR>function change_char_order(str,i,j)<BR>//where str is the string to be modified , i and j are the chars <BR>//that will be switched!<BR><BR>DO you know how?<BR>I tried to use:<BR>i= i-1<BR>j= j-1<BR>// to use correctly in charAt<BR> var1=str.charAt(i)<BR> var2=str.charAt(j)<BR>str.charAt(i)=var2<BR>str.ch arAt(j)=var1<BR>but didn&#039t Worked!<BR>and also:<BR>the "charAt()" didn&#039t worked inside function, even that the same code , but outside a function worked well!<BR><BR>Know how to explain it to me?

2. Dan Evans Guest

RE: Switching CHARs Position on STRINGS!! URGENT P

I don&#039t think you&#039re building the string properly. This works for me:<BR><BR>alert(change_chars("Dan Evans", 2, 5)); //Alerts DEn avans<BR><BR>function change_chars(str, i, j) {<BR> var strI = str.charAt(--i); //Because 1st char is index 0<BR> var strJ = str.charAt(--j); //we must decrement by 1<BR> return str.substring(0, i) + strJ + str.substring(i + 1, j) + strI + str.substring(j + 1, str.length); //Build the string<BR>}<BR>

3. Dan Evans Guest

p.s.

The charAt() method is one way (As far as I know) so you can&#039t simply say str.charAt(j) = "D". You have to build the string manually (I thought substrings would be easiest)<BR><BR>-Dan

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•