user411103
user411103

Reputation:

New line character as function parameter in Javascript

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

Upvotes: 3

Views: 7390

Answers (2)

ixx
ixx

Reputation: 32269

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

d("Hello\n\
World");

Upvotes: 2

Mike Samuel
Mike Samuel

Reputation: 120546

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

Upvotes: 3

Related Questions