views:

43

answers:

3

I have the follwing jQuery:

        $("#textArea").keyup(function(){
            var textAreaValue = $("textArea");
            if(!textArea.value.indexOf("some string")){
                textArea.value = textArea.value.replace("some string",null);
                alert("It was there!");
            }
        });


  • Is it normal for element.value.replace("some string",null); to replace "some string" with "null"as a string? And if normal can you please explain why?

  • I have tested it with element.value.replace("some string",""), and that works fine, so what would be the difference between null and ""?

Using FireFox 3.6.3, Thanks in advance.

+1  A: 

"" is an empty string..

null is something that indicates a deliberate non-value or undefined...

null is mostly used to initialize objects

and in str.replace(param1,param2), param1 and param2 should be a string or something that produces a string ( in param2 )... in that said,

var heart_type = 'images/unheart.png';
alert( heart_type.replace(".png",null));​

will alert images/unheartnull.. because null was treated as a string...

.replace() reference

Reigel
+1  A: 

The second parameter of String.replace is a required parameter, and it must be a string. See mdc and w3schools. It's not normal or safe to pass null, which is not a string. Don't be surprised if your code does not execute properly in all javascript engines.

Eric Mickelsen
+2  A: 

Seems like null has been type-casted to a String.

Try:

"a" + null // "anull"

Although you can't call toString() on a null object, it seems the null object is implicitly being converted to a String, which gives the string "null".

String(null) // "null"
Anurag
Passing `null` when a string is expected will not always have this result, and it is usually not a desired result anyway.
Eric Mickelsen
@tehMick - the behavior for String.prototype.replace as per [ECMAScript 5th ed.](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf) suggest that a null `replaceValue` should be replaced with the string `"null"`. It may be unexpected for other cases, but for String.prototype.replace, it's very much expected.
Anurag
@Anurag: Good call - "Otherwise, let newstring denote the result of converting replaceValue to a String." This may work for 5th ed. and this particular function, but then again, why pass `null` instead of `"null"` unless you're playing code golf? It serves only to confuse future readers of you code, since a naive interpretation would be that you are replacing matches with *nothing* rather than "null".
Eric Mickelsen
@tehMich - I agree with you. It's extremely unintuitive to use the `null` type as a sneaky replacement for the string `"null"`. The obvious interpretation to this, as you said, is that the matching text is being removed rather than replaced.
Anurag