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: coursesweb.net"; // with double quotes
// or
var variable_name1 = 'some text: coursesweb.net'; // 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).
<script>
// Incorrect
var a_name = 'CoursesWeb.net 'JS lesson''; // SyntaxError: missing ; before statement

// Correct
var a_name = "CoursesWeb.net \"JS lesson\"";
// or
var a_name = 'CoursesWeb.net "JS lesson"';
// or
var a_name = "CoursesWeb.net 'JS lesson'";
--></script>

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>

<script>
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];
</script>

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>

<script>
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;
}
</script>

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>

<script>
const email ='some_name@domain.net';

//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
if(is_em){
 document.write('The name from the address: "'+email+'" is: '+ is_em[1]);
}
</script>

Chaining methods

You can apply several chained methods to an object.
object.method1().method_2()
- 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>

<script>
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;
</script>

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>

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

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>

<script>
//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;
</script>

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

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag defines the clickable areas inside the image map?
<map> <img> <area>
<img src="image.jpg" usemap="#map1">
<map name="map1">
  <area shape="rect" coords="9, 120, 56, 149" href="#">
  <area shape="rect" coords="100, 200, 156, 249" href="#">
</map>
Which CSS property defines what is done if the content in a box is too big for its defined space?
display overflow position
#id {
  overflow: auto;
}
Click on the event which is triggered when the mouse is positioned over an object.
onclick onmouseover onmouseout
document.getElementById("id").onmouseover = function(){
  document.write("Have Good Life");
}
Indicate the PHP variable that contains data added in URL address after the "?" character.
$_SESSION $_GET $_POST
if(isset($_GET["id"])) {
  echo $_GET["id"];
}
JavaScript Strings

Last accessed pages

  1. PHP Simple HTML DOM Parser (12348)
  2. Node.js Move and Copy file (28270)
  3. Output or Force Download MP3 with PHP (5661)
  4. Get and Modify content of an Iframe (32094)
  5. Align DIVs on the same line (8342)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (250)
  2. Read Excel file data in PHP - PhpExcelReader (89)
  3. PHP Unzipper - Extract Zip, Rar Archives (74)
  4. The Four Agreements (73)
  5. The Mastery of Love (66)
Chat
Chat or leave a message for the other users
Full screenInchide