Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple .replace() doesn't seem to work

Status
Not open for further replies.

youradds

Programmer
Jun 27, 2001
817
GB
Hi,

I'm trying to replace " " with "_" in a username string, but even in the most basic form it doesn't seem to work?

Code:
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 31</title>
<script type="text/javascript" src="[URL unfurl="true"]http://domain.com/new_js/jquery.js"></script>[/URL]

</head>

<body>

<script>

function do_replace() {
	username_val = $('#comm_username').val();
	username_val.replace(/\s+/i, "_");
	alert("NEW: " + username_val);
}
</script>

<form onsubmit="return do_replace();">
<input name="comm_username" id="comm_username" />
<input type="submit" value="test" />
</form>

</body>

</html>


I've also tried:

Code:
	username_val.replace(" ", "_");

Any suggestions? Probably missing something silly :|

TIA

Andy
 
Hi

[ul]
[li]The [tt]replace()[/tt] method not alters the object itself, the modified string is only returned[/li]
[li]The use of the [tt]i[/tt] modifier is useless here, as case sensitivity has no effect on whitespace characters[/li]
[li]Your regular expression will replace only the first occurence, but I guess you want to replace all, so use the [tt]g[/tt] modifier[/li]
[/ul]
Code:
[highlight]username_val[teal]=[/teal][/highlight]username_val[teal].[/teal][COLOR=darkgoldenrod]replace[/color][teal]([/teal][fuchsia]/\s+/[highlight]g[/highlight][/fuchsia][teal],[/teal] [green][i]"_"[/i][/green][teal])[/teal]

Feherke.
 
Doh -knew it had to be something simple :D

This works perfectly now - thanks :)

username_val = username_val.replace(/\s+/gi, "_");
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top