JAvascript

Strings in Javascript

Strings

A string is simply text data (a string of characters). String literals can be represented with either single quotes, double quotes, or backticks. Backticks were introduced in ES6.

let userName = 'Sydney'; // valid string literal with single quotes
let email = "sydchako@gmail.com"; // valid string literal with double quotes
let job = `Software Developer`; // valid string literal with backticks. 

Strings can also be created from other data types using the String() function.

let intString = String(32);
console.log(typeof intString); //prints String
console.log(intString + intString); //prints 3232

var boolString = String(true);
console.log(typeof boolString); //prints string

let nullString = String(null);
//etc

toString() can also be used to convert Numbers, Booleans or Objects to Strings

var intString2 = (5232).toString();
var boolString2 = (false).toString();
var objString = ({}).toString();
console.log(objString);  //prints [object Object]
console.log(typeof objString); //prints string

Strings also can be created by using String.fromCharCode() method.

let charString = String.fromCharCode(104,101,108,108,111);
console.log(charString); //prints hello

Creating a String object using new keyword is allowed, but is not recommended as it behaves like Objects unlike a primitive string.

var obString = new String("I am a String object");
console.log(typeof obString);//prints object"
console.log(typeof obString.valueOf());//prints string

Escaping characters


let story = "Juliet said, "hello!"";

will produce an error like:


let story = "Juliet said, "hello!"";
                           ^^^^^
SyntaxError: Unexpected identifier

The reason being that, Javascript took the literal to be "Juliet said, " because the inner quotes around "hello!" are the sames as the opening and closing quotes, so there is no way of distinguishing between them. Hello is now treated as an identifier because it is now technically outside the quotes.

One way of correcting this is:


let story1 = 'Juliet said, "hello!" '; //single outer quotes, double inner quotes

Or


let story2 = "Juliet said, 'hello!' "; //the choice is yours

but what if Juliet said, "Don’t talk to me"? Lets see


let story3 = 'Juliet said, "Don't talk to me" ';

will produce an error like:

let story3 = 'Juliet said, "Don't talk to me" ';
                                ^
SyntaxError: Unexpected identifier

The outer single quote was closed by the apostrophe on Don’t
The literal became ‘Juliet said, "Don’. The t on Don’t is now the unexpected identifier.

Now let’s properly enclose the string literal


let story4 = "Juliet said, 'Don't talk to me' "; //Now valid

However, a better way is by escaping the quotes using a backslash (**). The backslash will signal that the string is not ending


let story5 = "Juliet said, \"Don't talk to me \" "; //The inner quotes are now escaped by \

console.log(story5); // prints Juliet said, "Don't talk to me "

A backslash can be printed by escaping it with another backslash


let story6 = "This is a \\";

console.log(story5); //prints This is a \

Special characters

A backslash is also used to represent certain nonprintable characters, such as newlines and arbitrary Unicode characters.

Newline (\n)

let bio = "My name is Ironman \n I created War Machine"
console.log(bio); //prints My name is Ironman 
                        // I created War Machine

Commonly used escape characters

\n new line
\r carriage return
\t tab

String concat

let  suitTemp  =  29.5; 
// 00b0 is the Unicode code point for the "degree" symbol 
const  message  =  "The current suit temperature is "  +  suitTemp  +  "\u00b0C";
console.log(message); //prints The current suit temperature is 29.5°C

The above code builds a string using string concat (+). String concatenation can be done with the + concatenation operator, or with the built-in concat() method on the String object prototype.
In ES6 this can also be accomplished using template strings as we shall see later.

let title = "Sir"; //string
let name = "Albert"; //string
let surname = "Einstein"; //string
let year = 1945 //number
let genius = true; //boolean

let fullname = title+" "+name+" "+surname;
console.log(fullname); //prints Sir Albert Einstein

let occupation = "physicist";
let sentence = name.concat(" ").concat("the").concat(" ").concat(occupation);
console.log(sentence); //prints Albert the physicist

let sentence2 = name.concat(" ", "the", " ", occupation);
console.log(sentence2); //prints Albert the physicist

//Strings can be concatenated with non-string variables 
//but that will type-convert the non-string variables into strings.

console.log(name.concat(year)); //prints Albert1945
console.log(title+ genius); //prints Sirtrue

If you put a number in quotation marks, it’s not a number, it’s a string.

let a = 5; //a is a number
let b = "3"; //b is a string

console.log(a); //prints 5
console.log(b); //prints 3
console.log(a+b); //prints 53 (string concat because 3 is a string)
console.log(b+a); //prints 35
console.log(a*b); //prints 15 (a and b have been treated as if both are numbers)

String Templates

In ES6 strings can also be built using string templates literals (backticks) instead of string concatenation.
Note the backticks used below instead of quotes

let  thrusterTemp  =  29.5; 
const  wrng  =  `The current thruster temperature is  ${thrusterTemp}\u00b0C`;
console.log(wrng); //prints The current thruster temperature is 29.5°C
var fullname = "Sir Albert Einstein";

//With template literals, you can do 
//string interpolation using ${variable} inside template literals:

var country = `Zimbabwe`;
var fact = `${fullname} never visited ${country}!`;
console.log(fact); //prints Sir Albert Einstein never visited Zimbabwe!