Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL
JavaScriptBasicsRunning a ScriptVariablesExpressions and OperatorsObjects.Properties.MethodsThe Date ObjectJavaScript StringsStringsRegular ExpressionsDefining RegExp PatternsBranches and ConditionsLoopsArraysArray MethodsSorting ArraysUser-Defined FunctionsCookiesWindowsFrames

Home > JavaScript > Stringsprinter version

JavaScript Strings

Strings are commonly used in JavaScript so there are a number of properties and methods provided to manipulate them (properties and methods are covered in the Ojects.Properties.Methods Tutorial).

String Literals

String literals may be enclosed with single or double quotes. Double quote characters may be contained in a single quote string or vice versa.

If variables are required to be written into a string then concatenation must be used as covered in the JavaScript Variables Tutorial.

Escape Sequences

Escape sequences are preceded by the \ character to signify that the characters are to be treated differently.

In a single quoted string if you wish to use the ' character then to avoid JavaScript treating the character as a string delimiter then it must be escaped with the \ character.

The only other escape sequence supported by single quoted strings is the \ character itself, which if used, must be escaped with \.

Single Quotes Escape Sequences
<script language="javascript" type="text/javascript">
    document.write ('It\'s a single quote string.');

    document.write ('Backslash \\ is used as an escape character.');
</script>


Strings also support a number of escape sequences including...



Finding the Length of a String

The number of characters in a string can be found from the length property.

Example of the Length Property
<script language="javascript" type="text/javascript">
    var name = "George Smith";
    var varlen = name.length;
    // This prints out 12
    document.write(varlen);
</script>


Changing Case

You can change the case of a string with the following methods.



Examples of Changing Case
<script language="javascript" type="text/javascript">
    var name = "George Smith";
    name = name.toUpperCase();
    // This prints out GEORGE SMITH
    document.write(name);

    name = name.toLowerCase();
    // This prints out george smith
    document.write(name);
</script>


Finding Characters within Strings

The indexOf() method allows you to find the first occurrence of a character or character combination within a string.

The method returns a numeric value with the beginning of the string considered as index zero.

If the character or character combination isn't found then the method returns -1.

Example of indexOf
<script language="javascript" type="text/javascript">
    var name = "George Smith";
    var position = name.indexOf('m');
    // This prints out 8
    document.write(position);
</script>


The method also accepts a second argument to allow you to begin the search after an index other than zero and takes the form
string.indexOf('m',7).

The lastIndexOf Method

The lastIndexOf() method works in exactly the same way as the indexOf() method but instead of returning the first character, or character combination, it returns the last.

The charAt() Method

This method will return a character at a given position.

Example of indexOf
<script language="javascript" type="text/javascript">
    var name = "George Smith";
    var char = name.charAt(0);
    // This prints out G
    document.write(char);
</script>


Extracting Substrings from Strings

JavaScript provides several methods for extracting substrings from strings.

The substring() Method

This method uses two arguments - an index value from the start of the string and a second index value for where to end the substring within the string.

If only the first argument is provided then it will return a substring from the index value to the end of the string.

Example of substring()
<script language="javascript" type="text/javascript">
    var name = "George Smith";
    var sub = name.substring(0,6);
    // This prints out George
    document.write(sub);
</script>


The substr() Method

This method works slightly differently to the substring() method. The first argument is the same but the second argument is the length of substring to be extracted.

Example of substr()
<script language="javascript" type="text/javascript">
    var name = "George Smith";
    var sub = name.substr(7,4);
    // This prints out Smit
    document.write(sub);
</script>


Replacing Characters within Strings

The replace() method allows you to replace characters, or character combinations, within strings.

The method takes two arguments. The character, or character combination, to be replaced and the character, or character combination to replace it.

Example of replace()
<script language="javascript" type="text/javascript">
    var name = "George Smith";
    name = name.replace("George","Fred");
    // This prints out Fred Smith
    document.write(name);
</script>


Previous - JavaScript The Date Object Previous - The Date Object     Next - Regular Expressions Next - JavaScript Regular Expressions


Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
Tips and TricksImage ReplacementUsing IncludesForm ValidationDebugging
Got any JavaScript Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.
Recommended Reading
Javascript the definitive guide

Javascript and DHTML cookbook

Pro javascript techniques

simply javascript