admin管理员组

文章数量:1405393

From Test.html I include a test.js that runs function d(). This function has a parameter a string that might contain "new line" characters (10 in ASCII), as per example below. However, when I am debugging this function, vars s and data include all characters except the new line, i.e., they contain string "HelloWorld" (length 10) instead of "Hello[charNewLine]World" (length 11).

Is there a way to pass a string with new line characters as parameter to a function in Javascript? Thank you.

Test.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=x-user-defined">
<title>JavaScript Scripting</title>
</head>
<body>
<script type="text/javascript" charset="x-user-defined" src="test.js">
</script>
</body>
</html>

test.js

function d(s) 
{
    var data = (s + "").split("");
    var dataLength = data.length;
    var t = [dataLength],n;

    for(n=0;n<dataLength;n++)
    t[n]=data[n].charCodeAt(0);
}
d("Hello\
World");

From Test.html I include a test.js that runs function d(). This function has a parameter a string that might contain "new line" characters (10 in ASCII), as per example below. However, when I am debugging this function, vars s and data include all characters except the new line, i.e., they contain string "HelloWorld" (length 10) instead of "Hello[charNewLine]World" (length 11).

Is there a way to pass a string with new line characters as parameter to a function in Javascript? Thank you.

Test.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=x-user-defined">
<title>JavaScript Scripting</title>
</head>
<body>
<script type="text/javascript" charset="x-user-defined" src="test.js">
</script>
</body>
</html>

test.js

function d(s) 
{
    var data = (s + "").split("");
    var dataLength = data.length;
    var t = [dataLength],n;

    for(n=0;n<dataLength;n++)
    t[n]=data[n].charCodeAt(0);
}
d("Hello\
World");
Share Improve this question asked Feb 25, 2012 at 23:46 user411103user411103
Add a ment  | 

2 Answers 2

Reset to default 3
d("Hello\
World");

contains a "line continuation".

The language specification says

The String value (SV) of the literal is described in terms of character values (CV) contributed by the various parts of the string literal.

...

The SV of LineContinuation :: \ LineTerminatorSequence is the empty character sequence.

which means that it contributes no characters to the value of the string literal.

To embed a newline in a string, just use \n as in

d("Hello\nWorld")

If you want to see the new line and also pass it in the string, use it this way:

d("Hello\n\
World");

本文标签: New line character as function parameter in JavascriptStack Overflow