About
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!
world!`;
Generate / Repeat
- Repeat
"string".repeat(10)
- or Array join
Array(11).join("a")
Function
Concat
"my string" + "my string"
"35" + "25"
Replace
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, "");
console.log(text);
where:
- 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
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.
Example:
let result = "blue is beautiful".match(/bl*/m);
console.log(result);
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")}`);
ReplaceAll
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");
console.log(text);
Length
s = "length";
console.log(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
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));
charAt
var s = "length"
for (var i=0;i<s.length;++i) {
console.log("Char at "+i+" is "+s.charAt(i));
}
Split
- String Separator
var s = "1,2,3"
console.log("The second element is "+s.split(',')[1]);
- Regexp Separator
var s = "my-name_is_foo";
s = s.split(/-|_/).join(" ");
console.log(s);
Substring
var s = "HelloWorld";
s = s.substring(0, "Hello".length+1);
s = s + " Nico";
console.log(s);
toLowerCase
var s = "HelloWorld";
console.log("Hello You !".toLowerCase());
toCapitalize
let capitalizeString = string.charAt(0).toUpperCase() + string.slice(1);
isString
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)
console.log(sWithoutPrefix);
Delete suffix
- If the suffix is known
let suffix = "pre";
let s = ` text ${suffix} `;
let sWithoutSuffix = s.trim().slice(0,-suffix.length)
console.log(sWithoutSuffix);
Pad
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;
console.log(month.toString().padStart(2,'0'));
To
integer
parseInt(string,base)
Example
let i = parseInt("5.01",10);