Javascript - String


The Text - String in javascript.

A string in JavaScript is encoded with the ucs-2 16-bit character set. An element of a JavaScript string is therefore a 16-bit code unit.

String properties and methods (such as length, charAt, and charCodeAt) all work at the level of code units not at the Unicode code points. Unicode code points <math>2^16</math> and above are represented by two code units, known as a surrogate pair.

Strings behave like sequences of UTF-16 code units (ie variable length).

Syntax (Declaration and Assignment)

String literal

String literal: A single quote ' or a double quote indicate string values.

var myVariable = 'Foo';
// is equivalent to
var myVariable = "Foo" ;

String Object

var myVariable = String(var);

Template literal (heredoc)

var myString = `hello!

Generate / Repeat

  • Repeat
  • or Array join



"my string" + "my string"
"35" + "25"


Replace uses generally a regular expression as first parameter.

The regexp have no quotes but two slashes / as enclosing character.

// Not 
var regexp = '/pattern/md'
// but
var regexp = /pattern/md

Example: Suppress comments lines

text = "// My beautiful comment\r\nmy beautiful code\r\n";
text = text.replace(/^[/]{2}[^\r\n]+[\r\n]+/mg, "");


  • The regexp pattern can be read as:
    • have no quotes but two slashes / as enclosing character.
    • ^ - the start of the pattern
    • [/]{2}: two backslashs
    • [^\r\n]: All characters excepts the end of line \r\n. The ^ character is a negation in a class.
    • + is a quantifier meaning one or more
    • mg are modifier that says respectively 'm': multiline matching, 'g': global match (find all matches rather than stopping after the first match)


match 1) uses generally a regular expression as first parameter.

The result returns:

  • an array of matches (depend on the g flag)
  • or null if no matches are found.


let result =  "blue is beautiful".match(/bl*/m);

The regexp have no quotes but two slashes / as enclosing character otherwise you need to create an regexp object.

// Not 
var regexp = '/pattern/md'
// but
var regexp = /pattern/md

Contains / Includes


var s = "HelloWorld";
if ( s.includes("Hello") ) {
   console.log("Hello You !");
console.log(`Does the string contains Hello: ${s.includes("Hello")}`);
console.log(`Does the string contains foo: ${s.includes("Foo")}`);


To replace all the character in a string, you need to add mg to the pattern of replace

The regexp have no quotes but two slashes / as enclosing character.

Example: Replace all x with a y:

text = "xxxxxxxxxxxxxxxxxxxxxxxx";
text = text.replace(/x/mg, "y");


s = "length";

The length property of Javascript (as all String function) returns the number of code unit not the number of character (ie code point). See the character length


charCodeAt return code units rather than code points.

s = "Hello Foo";
console.log("The string ("+s+") is made of character coded with one code units and has then a length of "+s.length);
console.log("First code unit of "+s+" is "+s.charCodeAt(0));

s= "𐌰";
console.log("The character "+s+" is encoded with two code units and has then a length of "+s.length);
console.log("First code unit of "+s+" is "+s.charCodeAt(0));
console.log("Second code unit of "+s+" is "+s.charCodeAt(1));


var s = "length"

for (var i=0;i<s.length;++i) {
    console.log("Char at "+i+" is "+s.charAt(i));


  • String Separator
var s = "1,2,3"

console.log("The second element is "+s.split(',')[1]);
var s = "my-name_is_foo";
s = s.split(/-|_/).join(" ");


var s = "HelloWorld";
s = s.substring(0, "Hello".length+1);
s = s + " Nico";



var s = "HelloWorld";
console.log("Hello You !".toLowerCase());


let capitalizeString = string.charAt(0).toUpperCase() + string.slice(1);


let isString = function(s){
    if (typeof s === 'string' || s instanceof String){
       return true;
    } else {
       return false;
let foo = 2;
let bar = "2";
console.log(`foo ${foo} is a string ? `+isString(foo));
console.log(`bar ${bar} is a string ? `+isString(bar));

Delete prefix

  • If the prefix is known
let prefix = "pre";
let s = ` ${prefix} text `;
let sWithoutPrefix = s.trim().slice(prefix.length)

Delete suffix

  • If the suffix is known
let suffix = "pre";
let s = ` text ${suffix} `;
let sWithoutSuffix = s.trim().slice(0,-suffix.length)


Pad adds a character to a string until a certain length is reached.

You can pad (add the character):

  • at the beginning of the string with padStart 3)
  • at the end with padEnd

Example with in a date string where you need to have two digits for the month.

let month = 2;



To Javascript - Integer



let i = parseInt("5.01",10);



Documentation / Reference

Discover More
Chrome Devtool Xhr Fetch Request
Browser - XMLHttpRequest (XHR) API

The XMLHttpRequest is a web api function that performs an resource fetch with an Aysnchronous HTTP request XMLHttpRequestAPIAJAX programmingfetch API The status of an XHR request. Value Constant...
D3 Csv Console Log
D3 - Csv Function (CSV from an URL )

This section talks the function d3.csv that parse a CSV file. To parse a CSV string, see . Reference: Csv The csv file or string must...
Card Puncher Data Processing
D3 - DSV

d3-dsv is a library to parse a DSV string (not file) into an array of rows where the property are the headers. To parse a CSV file, see . stringnumbers A template string...
Card Puncher Data Processing
Datacadamia - Data all the things

Computer science from a data perspective
How to manipulate and show a Date Time in Javascript?

In javascript, date time information is represented in a a date object that: encapsulates the epoch time in milliseconds is timezone-agnostic returns the number of milliseconds...
Javascript - Array

array in Javascript can contain any type of data. Different types of values can be stored within the same array Because arrays are special objects (as typeof implies), they can also have properties, including...
Javascript - Boolean (Truthy|Falsy)

in Javascript. JavaScript defines a list of specific values that are considered “falsy” because when coerced to a boolean, they become false. Any other value not on the “falsy” list is automatically...
Javascript - Character

This article is the character representation and manipulation in Javascript (ie code point). They: are all unicode UTF-16 character are an element in a string starting at the index 0. may have...
Functional Programming in Javascript

Functional Programming in Javascript in javascript. array operationsDoc To get the cookies All function...
Javascript - Integer

Integer aren't implemented in javascript, only double exists. See With integers, you have to take care that all calculations fit within the range between –2^53 and 2^53, but you don’t have to worry...

Share this page:
Follow us:
Task Runner