0

Here's my function:

CSS_Left = '450px';
CSS_Left.replace('px', '');
alert(CSS_Left);

It returns '450px'

Here's an example:

http://jsfiddle.net/D2Mgb/

I want it to replace 'px' with nothing.

3

4 Answers 4

4

In JavaScript, Strings are immutable.

All types except objects define immutable values. Specifically, strings are immutable (unlike in C for instance).

So, str.replace returns a new string. Try this instead:

CSS_Left = CSS_Left.replace('px', '');

Or if you don't want to overwrite the original string, just do it in the alert call

alert(CSS_Left.replace('px', ''));

It's worth noting that .replace can also take a regexp. Though it's not necessary in your case, you could do something like this to achieve the same result

CSS_Left = CSS_left.replace(/px$/, '');
Sign up to request clarification or add additional context in comments.

3 Comments

I can't believe I missed that X( . Thanks a lot! That was confusing me.
Moreover, String objects are immutable. You cannot edit them, only create modified new instances.
@LexLythius, I'll make a note. Thanks for your review.
3

Because .replace() return a new string. If you want to update the old string you should write: CSS_Left = CSS_Left.replace('px', '');

Comments

0

I am not sure, but the function replace() creates a new variable. Try this :

var CSS_Left = '450px';
CSS_Left = CSS_Left.replace('px', '');
alert(CSS_Left);

Comments

0

The output of the replace call needs to be reassigned to CSS_Left

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.