String and All about Strings
String is a sequence of letters, numbers, special characters and arithmetic values or combination of all. Strings can be created by enclosing the string literal (i.e. string characters) either within single quotes ('
) or double quotes ("
), as shown in the example below:var str = 'Hello World!'; // Single quoted string var str = "Hello World!"; // Double quoted string
String Escape Sequences:
Some characters cannot be typed using keyboard. For that we have escape sequences:
\n
is replaced by the newline character\t
is replaced by the tab character\r
is replaced by the carriage-return character\b
is replaced by the backspace character\\
is replaced by a single backslash (\
)
var str1 = "My name is John \n I like to read.";
document.write("<pre>" + str1 + "</pre>"); // Create line break
var str2 = "C:\Users\Documents";
document.write(str2); // Prints C:UsersDownloads
var str3 = "C:\\Users\\Documents";
document.write(str3); // Prints C:\Users\Downloads
var str1 = "The fast dog ran and fetch \b the ball";
document.getElementById("paragraph").textContent = (str1);
Thought-worthy Note: Before we move on with the tutorial, you would notice an error in the compiler when using document.write method. Though this method works, it has several drawbacks and it's advised not to use it. So we will abandon it right now and use more efficient ways to display out out. Here are few reasons why it's advisable not to use document.write
- It does not work with XHTML
- It's executed after the page has finished loading and may overwrite the page, or may write a new page or sometimes not even load at all.
- It randomly executes when encountered. And cannot be injected at a given node point.
- It effectively writes serialized text similar to .innerHTML and DOM does not work that way. This results in unnecessary bugs.
From this point on, please use this HTML as your starting point and we will display all our results in the paragraph tag. In easier language all our outputs will be written inside the paragraph.
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Javascript in depth</title>
</head>
<body>
<p id="paragraph"></p>
</body>
</html>
String Operations: Javascript provides several methods and properties to perform operations on strings.
1. String length: Length property returns the length of the string.
var str1 = "I am feeling very good today";
document.write(str1.length + "<br>");
var str2 = "This is a first line and \n new paragraph starts here.";
document.write(str2.length); // Prints 30, because \n is only one character
No comments:
Post a Comment