[SOLVED]jQuery replace.

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

[SOLVED]jQuery replace.

Post by JellyFish »

Hey, I'm trying to take the value of an input element and and place into a h2 element. So I'm using jquery to do this.

Code: Select all

$("#theh2").text($("#theinput").val());
But here's the problem. If I have two spaces in the input element the h2 element would only have one. So I figured:

Code: Select all

$("#theh2").text($("#theinput").val().replace(" ", " ");
would suffice. But results are not as expected:

"This and That" becomes "This and  That"

This is clearly not what I intended. Why isn't the [ ]s working?

I appreciate someone making sense out of this.

Thanks for reading. :D
Last edited by JellyFish on Wed Nov 07, 2007 2:20 am, edited 2 times in total.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

replace() is not a jQuery method, it's part of javascript and expects the match parameter to be a regex.

Try matching /\s/g instead of a space.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I think the problem has to do with the use of the text method.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

The code seems fine, and works for me. except, of course for your missing close-paren (which I assume is a typo here (or your script would error)
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Post by JellyFish »

Damn it. I thought I deleted this post. Sorry guys, for those of you who are reading the solution is:

Code: Select all

$("theh2").html($("#theinput").val().replace(" ", " "));
use html() rather then text().
Post Reply