Click to See Complete Forum and Search --> : using replace() in a loop


therealphil
11-04-2003, 05:53 AM
I have a string, input by the user that I put through validation which replaces any spaces (" ") with a hyphen ("-").

The problem is that if there is more than one space, only the first space is replaced. I have tried using do/while to create a loop, but that just makes the browser crash.

The end result should be that any string, regardless of how many spaces it has, is replaced with a string that has hyphens in place of spaces.

I have attached the page where it all happens.

Any help?
Thanks, Phil

Charles
11-04-2003, 06:27 AM
<script type="text/javascript">
<!--
alert('fee fie foe fum'.replace(/\s+/g, '-'))
// -->
</script>

The "replace()" method works much better if you use a Regular Expression (http://devedge.netscape.com/library/manuals/2000/javascript/1.3/guide/regexp.html).