Strings
Strings can be created directly via string literals. Those literals are delimited by single or double quotes. The backslash (\) escapes characters and produces a few control characters. Here are some examples: 'abc' "abc" 'Did she say "Hello"?' "Did she say \"Hello\"?" If you need to change the case of a string of text you can use the two inbuilt methods
toUpperCase
and
toLowerCase.
The
indexOf
method tells you if a string of text contains a particular character, the @ sign in an email address for example. It won't check every occurrence of the character, but just the first one. If you want the character returned rather than its position number then you can use the Javascript string method charAt. var character = email.charAt( at_sign ); Sometimes, you want to grab characters from a string. For example, you can grab the last four letters from an email address and see if they end in .com. You can do this with the Javascript method substr. You can split up strings of text with the Javascript split method. In between the round brackets of split you type an optional delimiter. The delimiter is how the various parts of the string are separated. This might be with a comma, a semicolon, a space, etc. The delimiter needs to go between quote marks. When you split a string you turn it into an array.
The Javascript join Method
You can join strings of text together with the join method.
String Length
The length of a string is found in the built in property length: Example var txt = "textcontent"; var sln = txt.length;
Special Characters
Because strings must be written within quotes, JavaScript will misunderstand this string: var y = "Text "quoted text" text. The string will be chopped to "Text ". The solution to avoid this problem, is to use the \ escape character. The backslash escape character turns special characters into string characters: Example var x = 'It\'s alright'; var y = "Text\"quoted text\" text." The escape character (\) can also be used to insert other special characters in a string. Code Outputs \' single quote \" double quote \\ backslash \n new line \r carriage return \t tab \b backspace \f
Breaking Long Code Lines
The safest way to break a long string is to use string addition: document.getElementById("demo").innerHTML = "Text" + "More text";
String Operators
Strings are concatenated via the plus (+) operator, which converts the other operand to a string if one of the operands is a string. String Methods Strings have many useful methods > 'abc'.slice(1) // copy a substring 'bc > '\t xyz '.trim() // trim whitespace 'xyz' > 'mjlnir'.toUpperCase() 'MJLNIR' > 'abc'.indexOf('b') // find a string 1 > 'abc'.indexOf('x') -1
up