Javascript Course

First must know what objects are in programming and the fundamental concepts of the object-oriented programming (OOP), because the string is recognized as an object in JavaScript.
JavaScript isn't a object-oriented (OO), such as C++ or Java, but is based on objects.
In the world around us the objects are, for example: a book, a car, a television ..., In JavaScript the object s are, for example: a form, a window, buttons, images, strings ...
JavaScript sees all elements of a page as objects.
An object is a collection of values called properties.
When a property is function, it’s referred to as a method.

The String object

There is various ways to create a string: using the new keyword or with the literal form, surrounding characters with either single quotes (') or double quotes (").

var instance_name = new String('string value here'); // using the 'new' keyword

// Literal form
var variable_name1 = "some text:"; // with double quotes
// or
var variable_name1 = 'some text:'; // with single quotes
- The most indicated way is the literal form (with quotes).
But whichever quote you use (single or double), you can’t use it again in the middle of the string because that will end the string early.
However, you can escape any character with a backslash (\) to solve this or use single quote inside double quotes (and vice versa).
// Incorrect
var a_name = ' 'JS lesson''; // SyntaxError: missing ; before statement

// Correct
var a_name = " \"JS lesson\"";
// or
var a_name = ' "JS lesson"';
// or
var a_name = " 'JS lesson'";

Strings have one built-in property, length - returns the number of characters in a string.
let str ='Tutorial JS';
let nr_chr = str.length; // 11
You can read in JS any character from a string using the index number. The first character has index 0 (str[0]), the second character has index 1 (str[1]), and so on.
- Example, displays in a Div the number of characters of a string and the third character (index 2).
<div id='dv1'>Did you smiled today?</div>

let str ='some_str';

//shows in #dv1 the number of character in 'str' and the third character
document.getElementById('dv1').innerHTML ='The string "some_str" has '+ str.length +' characters; the third is: '+ str[2];

Using String Methods

The String object contains many methods that can be useful in working with strings in JavaScript. A list of methods for strings can be found on the page: Methods of the String object in JS
- Here is a few examples with some of the string object methods.

Example with indexOf()

The indexOf() method is useful when you want to check if a string contains a specified substring.
The str.indexOf(s2) returns the position of the first occurrence of the substring 's2' in 'str', or -1, if the substring is not found.
<div id='dv1'>Example with indexOf().</div>

let str ='In the spirit of freedom.';

//if str contains 'spirit', adds the starting index in #dv1
var ix = str.indexOf('spirit');
if(ix !=-1){
 document.getElementById('dv1').innerHTML ='The word "spirit" starts from the index: '+ ix;

Example with match()

The match() method is useful to compare a string with a regular expression (RegExp). It returns an array with the matches or 'null'.
- Example, check if a string is a valid email address and gets the name from the address.
<div id='dv1'>JavaScript example with match().</div>

const email ='';

//is_em is an arra like: ['email', 'name', 'domain'], or null
var is_em = email.match(/^([A-z0-9]+[A-z0-9._%-]*)@([A-z0-9_\-\.]+\.[A-z]{2,5})$/i);

//if email is a valid address writes the name
 document.write('The name from the address: "'+email+'" is: '+ is_em[1]);

Chaining methods

You can apply several chained methods to an object.
- Example with replace() and trim().
The str.replace(s0, s2) method replaces in 'str' the matched substring 's0' with the value from 's2'.
The str.trim() method trims whitespace from the beginning and end of the string.
In the following example, the characters '<' and '>' are replaced in a HTML string with their HTML entities, and the resulting string is added into a Div.
<div id='dv1'> JavaScript example with methods chaining.</div>

let htm ='<h3>Today is a Happy Day</h3>';

//replace < si > from htm with their html entities, apply trim() and adds the string in #dv1
htm = htm.replace(/</ig, '&lt;').replace(/>/ig, '&gt;').trim();
document.getElementById('dv1').innerHTML = htm;

Adding quotes and special characters in string

When you want to add quotes into a string you must take in consideration the quotes used to define the string.
Double quotes can be added normally in a string defined with simple quotes (and vice versa).
- Syntax:
var str ='A text with "double" quotes';

var str ="A text with 'simple' quotes";

The same type of quotation marks as those used to define the string can be added by escaping (preceded by '\').
- Syntax:
var str ='A text with \'simple quotes\' as those that define this string.';

var str ="Another text with \"double quotes\", as those that define this string.";

Besides quotes, there are other special characters that must be escaped when are added in string.
Here's a list of these characters:
- Example, adding in a <pre> a string with multiple line, and contains quotes and backslash.
<pre id='pr1'>HTML content, object string.</pre>

let str ='A string defined with \'simple quotes\', \n added with backslash \\, \n and contains also "double quotes".';
document.getElementById('pr1').innerHTML = str;

Template string

The Template string is added between the accent characters ( `...` ).
This type of String allows to create strings with new lines without '\n' and can contain variables and JS expressions that will be executed directly in that string.
- Syntax:
var tmp =`string text line 1
 Line 2 and ${js_expression} JS expression.`;
- js_expression can be a JavaScript variable, call of a function or JS expression with values. These are added between: ${} and are executed like any JavaScript code.

Example, a string with multiple lines and html code with dynamic content.
<pre id='pr1'>Template string, HTML content</pre>

//defines variables and an arrow function to be used in the template string
let str_st ='Template string';
let arr =[8, 0];
const sumXY =(x, y)=>(x+y);

//the template string
var tmp =`<h3>This is ${str_st} from JavaScript</h3>
Calling the function sumXY(): sum 7+8 = ${sumXY(7,8)}
And a new line with <b>JS expression, 8*0 = ${arr[0] * arr[1]}</b>.`;

//adds the resulted string in #pr1
document.getElementById('pr1').innerHTML = tmp;

Inside a template string you can add the accent character escaped with backslash (\`).

Daily Test with Code Example

Which tag adds a new line into a paragraph?
<b> <br> <p>
First line ...<br>
Other line...
Which CSS property can be used to add space between letters?
text-size word-spacing letter-spacing
#id {
  letter-spacing: 2px;
What JavaScript function can be used to get access to HTML element with a specified ID?
getElementById() getElementsByTagName() createElement()
var elm = document.getElementById("theID");
var content = elm.innerHTML;
Click on the "echo" correct instruction.
echo "" echo ""; echo """;
echo "Address URL:";
JavaScript Strings

Last accessed pages

  1. Simple arithmetic calculator in PHP (2104)
  2. querySelector and querySelectorAll (30064)
  3. array_map and array_search in JavaScript (4059)
  4. ActionScript 3 - Change MovieClip Color (8965)
  5. Display data from PHP Array, or MySQL in HTML table (26805)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (326)
  2. PHP Unzipper - Extract Zip, Rar Archives (86)
  3. Read Excel file data in PHP - PhpExcelReader (82)
  4. The Mastery of Love (78)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (65)