When writing JavaScript code, one of the crucial elements you’ll use more frequently is the JS strings. You can use them the majority of the time when coding them to store and manipulate text.

Additionally, a JavaScript string contains characters or words you can write inside quotes. Strings are primitive values in JavaScript and are constructed from literals.

Furthermore, you can choose to define strings as objects with the keyword new. There are several ways you could manipulate strings to suit your custom programming needs. Let’s start by learning how to create strings using JavaScript.

How to Create Strings

You can easily create a JavaScript string by simply initializing and assigning values to a variable. The only difference is that strings are strictly characters. You can create a JavaScript string from string literals or as an object using the String() constructor.

// sample codes showing different ways to declare a string variable in JS

const strgA = "This is a string Variable"; // we used double quotes here
const strgB = 'This another string primitive'; // we used single quotes here

const strgC = `This also, is another string primitive`; // we used template literals here

const strgD = new String("A String object"); // we used the new keyword to create a string here. A new keyword creates an object string


console.log(strgA, "\n ", strgB,  "\n ",  strgC,  "\n ", strgD)

The backtick character “or single or double quotes” can be used to specify a string literal. A template literal specifies expressions that can be interpolated. When you want to include the value of a variable or expressions into a string, you use the template string (using backticks).

// this code shows how you can directly interpolate strings with integers.

let amountLoaned = 500, rateForPayment = 0.02, paymentPeriod= 2;
let resultAfterCompute = `The total amount you must pay after 2 years is: ${amountLoaned*(1 + rateForPayment*paymentPeriod)}`;


console.log(resultAfterCompute)

As shown below, the template string can span multiple lines, which is not possible with a single or double-quoted string.

let strgA = `This example shows a
            multi-line
            string`;

/*let strgB2 = "Using
Quotes
Will make this
code has issues"; */

Note: When you create a string as an object and a variable, they are not comparable. This means that the compiler does not see both of them as being the same, even though they are similar to the physical eye. So it is recommended that you do not use the object format to create strings.

Example:

let xNm = "John"; // In this example, xNm here is a variable
let yNm = new String("John"); // while yNm is an object

Strings Comparison

The operators >, ==, and === can be used to compare two strings. 

Depending on the sequence of characters in the string, the mathematical operators  < and > compare two strings and return a boolean (true or false).

While the == operator compares the contents of strings and the === operator compares the reference equality of strings.

Example:

console.log("a" < "b"); //here it checks for a < b, the answer is true(remember ordering these alphabets based on position a =1, b= 2)
console.log("b" < "a"); //here the answer is false because b is greater than a, not less than


console.log("Apple" == "Apple"); //true as both are the same
console.log("Apple" == "apple"); //false, the other started with a lowercase

console.log("Apple" === "Apple"); //true, but look the same and create with the same constructs
console.log("Apple" === "apple"); //false, construction problem

How to Find the Length of a Specific String

When determining a string’s length, we must count each character separately. The result should show how many characters are in the string. You can use the built-in length property to speed up this process.

Example

let AlphaConsonants= "BCDFGHJKLMNPQRSTVWXYZ";
 
let length = AlphaConsonants.length; // using length function to get the number of character
console.log(length); // result = 21

String Concatenation

The join() method, the + operator, template literals, and the concat() method can all be used to combine strings in JavaScript.

Example 1:

let strgA = 'Hello ';
let strgB = "World ";

let strgC = strgA + strgB ;
let strgD = strgA.concat(strgB);


// example showing the different ways to concat strings
const UserName = 'Nitro';
const userCountry = 'UK';

// We are using the concat() here
const strOutput1 = 'My name is '.concat(UserName, ', and I\'m from ', userCountry);

// we use the + operator
const strOutput2 = UserName + ' ' + userCountry;

// we are using the template literal here
const strOutput3 = `My name is ${UserName}, and I'm from ${userCountry}`;



console.log(strOutput1);// concat()

console.log(strOutput2); // + operator

console.log(strOutput3); // template


// we are using the .join() here. It is best used to join array elements

const strgE = ['Nitro', ' ', 'programmer'].join(' ');

console.log(strgE);

Conclusion

In this article, we learned about strings and how to declare and concatenate Javascript strings.

Categorized in: