Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Javascript replace()


ghost's Avatar
0 0

Is there any way to replace every other character? I have something like this

document.write(0 + i);
document.write(8 + i);
document.write( -1 + i);
document.write(6 + i);
document.write(3 + i);

(There's actually a bunch more of it, but this should work to show you) and I want to change every other + to a - I thought that this would work

.replace(/[+](?= i[)];document.write[(]\d* [+])/g, "-")

but when I tried it, it looped through the string a bunch of times, and ended up being like

              • +.

Is there any way to only replace every other character with replace() in javascript? Or is there a way to replace the characters without replace()?


ghost's Avatar
0 0

I don't understand the code, but try running it through a conditional loop that replaces the character only if the condition is met. I would recommend using a modulo and a if else statement. I'll get back to you with some exemplary code.


ghost's Avatar
0 0
<html>
<body>
<script language="javascript" type="text/javascript" >
function js_replace()
{
	var store="+++++++++++++++++++++++++++++";
	var somevar="";

	for(var i=0; i<store.length; i++)
	{
		storechar=store.substring(i,i+1);

		if(i%2 == 1)
		{
		somevar+="-";
		}
		else
		{
		somevar+=storechar;	
		}
	}
	alert(somevar);	
}
</script>
<input type="button" onClick="js_replace()"/>
</body>
</html>

I had to use something else instead because the replace() is not best when using loops IMHO. It works by initializing a blank string. Next a for loop is declared. Afterwards, there are two conditionals. The first one appends the minus sign if i is odd. The second appends the character in the variable store if it is even. It runs throughout the entire and when it is done, it alerts the newly made string.