A string is a string of letters, digits, punctuation characters, and so on--it is the JavaScript data type for representing text. As we saw in Chapter 2, Lexical Structure, string literals may be included in your programs by enclosing them in matching pairs of single or double quotes.
One of the built-in features of JavaScript is the ability to concatenate strings. If you use the + operator with numbers, it adds them. But if you use this operator on strings, it joins them by appending the second to the first. For example:
msg = "Hello, " + "world"; // produces the string "Hello, world" greeting = "Welcome to my home page," + " " + name;
To determine the length of a string--the number of characters it contains--you use the length property of the string. If the variable s contains a string, you access its length like this:
s.length
There are a number of methods that you can use to operate on strings. For example, to find out what the last character of a string s is, you could use:
last_char = s.charAt(s.length - 1)
To extract the second, third, and fourth characters from a string s, you would write:
sub = s.substring(1,4);
To find the position of the first letter `a' in a string s, you could use:
i = s.indexOf('a');
There are quite a few other methods you can use to manipulate strings. You'll find full documentation of these methods in the reference section of this book, under the headings "String", "String.charAt", and so on.
When we introduce the object data type below, you'll see that object properties and methods are used in the same way that string properties and methods are used in the examples above. This does not mean that strings are a type of object. In fact, strings are a distinct JavaScript data type. They use object syntax for accessing properties and methods, but they are not themselves objects. We'll see just why this is at the end of this chapter.
Note that JavaScript does not have a char or character data type, like C, C++, and Java do. To represent a single character, you simply use a string that has a length of 1.
file: /Techref/language/JAVA/SCRIPT/definitive/ch03_03.htm, 5KB, , updated: 2019/10/14 15:00, local time: 2024/12/23 04:59,
3.137.175.83:LOG IN
|
©2024 These pages are served without commercial sponsorship. (No popup ads, etc...).Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE. Questions? <A HREF="http://sxlist.com/techref/language/JAVA/SCRIPT/definitive/ch03_03.htm"> [Chapter 3] 3.3 Strings</A> |
Did you find what you needed? |
Welcome to sxlist.com!sales, advertizing, & kind contributors just like you! Please don't rip/copy (here's why Copies of the site on CD are available at minimal cost. |
Welcome to sxlist.com! |
.