admin管理员组

文章数量:1421176

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.

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.

Share Improve this question edited Jun 16, 2010 at 4:12 Babiker asked Jun 16, 2010 at 4:07 BabikerBabiker 18.8k28 gold badges82 silver badges127 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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"

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.

"" 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

本文标签: jqueryPassing null as a param for replace() in javascript behaving weirdStack Overflow