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 HTML5 tag defines marked text? (can be used to highlight parts of text)
<mark> <embed> <span>
<p>Free corses: <mark>coursesweb.net</mark> for Web Development.</p>
Which CSS pseudo-class adds a style to an element when the mouse is over it?
:focus :hover :active
a:hover {
  font-weight: bold;
  color: #00da01;
}
Click on the function which returns a string value that represents the number rounded to the x digits after the decimal point.
toPrecision(x) toFixed(x) floor(x)
var num = 12.34567;
num = num.toFixed(2);
alert(num);       // 12.35
Indicate the PHP function which reads an entire file into an array.
[) file() readfile()
$arr = file("a_file.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
var_export($arr);
JavaScript Strings

Last accessed pages

  1. Convert XML to JSON in JavaScript (17992)
  2. Get Duration of Audio /Video file before Upload (6242)
  3. Read Excel file data in PHP - PhpExcelReader (58996)
  4. Ajax-PHP Chat Script (37151)
  5. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (10380)

Popular pages this month

  1. Read Excel file data in PHP - PhpExcelReader (524)
  2. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (451)
  3. Get Attribute (ID, Class, Name, Title, Src) with jQuery (329)
  4. Insert, Select and Update NULL value in MySQL (316)
  5. PHP getElementById and getElementsByTagName (307)