Page 1 of 1

[SOLVED]jQuery replace.

Posted: Sat Nov 03, 2007 6:59 pm
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

Posted: Sun Nov 04, 2007 4:14 am
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.

Posted: Sun Nov 04, 2007 6:40 am
by feyd
I think the problem has to do with the use of the text method.

Posted: Sun Nov 04, 2007 10:30 am
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)

Posted: Wed Nov 07, 2007 2:19 am
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().