...

View Full Version : JS: Insert a character at every 2nd character in a string



Jazzo
10-19-2008, 03:31 PM
I want to know if it's possible to insert a character at every 2nd character in a string. By that I mean like taking the string:

1234567890

and the character "a" and turning it into

12a34a56a78a90

Would that be possible? Help is greatly appreciated.

BTW, I am a Javascript novice. :-)

Philip M
10-19-2008, 04:15 PM
<script type = "text/javascript">
var str = "1234567890";
str = str.replace(/(\S{2})/g,"$1a");
str = str.replace(/a$/,""); // if you do not want the final a
alert (str);
</script>


Quizmaster: Who was the Norwegian Explorer who first reached the South Pole?
Contestant: Sherpa Tenzing

Arty Effem
10-19-2008, 04:15 PM
I want to know if it's possible to insert a character at every 2nd character in a string. By that I mean like taking the string:

1234567890

and the character "a" and turning it into

12a34a56a78a90

Would that be possible? Yes it's certainly possible, for instance:alert("1234567890".replace(/(.{2})/g,"a$1"));, but if this is a homework question
12 Year Old Magicianyou'll have to conjure a more rudimentary method.

shyam
10-19-2008, 04:17 PM
I want to know if it's possible to insert a character at every 2nd character in a string.
yes. its possible :)

Jazzo
10-19-2008, 04:24 PM
Thank you all very much :)

mrhoo
10-19-2008, 04:33 PM
Another way is to use a regular expression to match all the two character substrings.
A match returns an array, so you can join it with the characters you want to insert.

You'll need to take care of a trailing single character.

string.length&#37;2 will tell you if the length is odd- leaves a remainder after dividing by 2.
If so, you need to remember the final character, since it won't be returned in the array of two character matches.


var s= '11231234233440';
var L= s.length;
L=(L%2) ? 'a'+ s.charAt(L-1) : '';
var M= s.match(/(.{2})/g) ;
if(M) s= M.join('a')+ L;

alert(s)

Philip M
10-19-2008, 04:40 PM
.....you'll have to conjure a more rudimentary method.



<script type = "text/javascript">
var str = "1234567890";
var newstr = "";
var c;
for (var i = 0; i<str.length; i++) {
c = str.charAt(i);
newstr = newstr + c;
if (i%2 != 0 && (i<str.length-1)) {
newstr = newstr + "a";
}
}
alert (newstr);
</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum