i need to write a function to remove consecutive slashses from a string

i wrote this

for( i=0; i!=b; )
	   {	
		var slashone = strname.indexOf('/',i+1)
		i=slashone
		var slashtwo = strname.indexOf('/',i+1)
		i=slashtwo
		//alert("index of slash one" + slashone)
		
		//alert("index of slash two" + slashtwo)	
		if( slashone == (slashtwo-1))
		 {
		 alert("Remove Consecutive Slashes")
		// form..focus();
		 form.NAME.focus();
		 return false;
		 
		 }	      
		//	break; 
	   }

this works only for the first occurence
not there after
ie it works for a//b
but doesn't work for a//b//c

Recommended Answers

All 3 Replies

Here is an example script that can help you learn Regular Expressions.

<html>
<head>
<script type="text/javascript">
function removeSlash(string, searchFor) {
	// This searches for all occurrences of searchFor that occurs more than once
	// {2,} means 2 or more repeats
	// The second param, "i", marks the search case-insensitive (if you need to remove letters)
	// If you want to remove ALL multiple occurrences, change the second param to "gi"

	var RegEx = new RegExp("(" + searchFor + "){2,}", "i");
	return string.replace(RegEx, searchFor);
}
</script>
</head>
<body>

<script type="text/javascript">
var myString = "a////b//c//d";
document.write("Original string: " + myString + "<br/>");

var fixedString = removeSlash(myString, "/");
document.write("Fixed string: " + fixedString); // Should return "a/b//c//d"
</script>

</body>
</html>
commented: thanks... +1

regular expressions seemed a lil difficult, i'll go through them some time later...
i wrote this for my problem....

function RemoveConsecutiveValues(strString, strConValue)
{
while (strString.indexOf(strConValue + strConValue) >= 0)
{
strString = strString.replace(strConValue + strConValue, strConValue);
} 
while (strString.indexOf(strConValue) == 0)
{	 
 strString=strString.replace(strConValue , "");
}	
	
while(strString.lastIndexOf(strConValue) == (strString.length - 1))
{
strString= strString.substring(0,strString.lastIndexOf(strCon  Value))
}  
	
return strString;

}

thanks everyone !!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.