DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for A Thorough View of Strings in JavaScript
Indira Kumar A K
Indira Kumar A K

Posted on • Updated on

A Thorough View of Strings in JavaScript

Introduction

In JavaScript, textual data is stored as strings. There is no separate type for a single character.
The internal format for strings is always UTF-16, no matter what the pages use. The size of a JavaScript string is always 2 bytes per character. Any string can be created by enclosing the value with single or double quotes or backticks.

Example:

let single = 'single-quoted';
let double = "double-quoted";
let backticks = `backticks`;
Enter fullscreen mode Exit fullscreen mode

Here single and double quotes are the same. But backticks help us embed expressions into strings by just wrapping ${} around

alert(`1 + 2 = ${1 + 2}.`); \\ 1 + 2 = 3.
Enter fullscreen mode Exit fullscreen mode

Backticks also allow you to span your texts to multiple lines which is not the same case with quotes.

let studentsList = `Guests:
 * Indira
 * Suraj
 * Valli
`;
Enter fullscreen mode Exit fullscreen mode

Tagged Templates:

Backticks are a blessing in another way too. You can use them to format strings using template functions. Here is an example explaining the same

const person = "Kumar";
const age = 19;

function myTag(strings, personExp, ageExp) {
  const str0 = strings[0]; // "That "
  const str1 = strings[1]; // " is a "
  const str2 = strings[2]; // "."

  const ageStr = ageExp > 99 ? "centenarian" : "youngster";

  // We can even return a string built using a template literal
  return `${str0}${personExp}${str1}${ageStr}${str2}`;
}

const output = myTag`That ${person} is a ${age}.`;

console.log(output);
// That Kumar is a youngster.
Enter fullscreen mode Exit fullscreen mode

Here, myTag is the tagged template that processes the strings, here "that", "is a", "." will be passed as an array of strings, then the expression ${person} is passed to personExp, and ${age} is passed to ageExp.

Escape sequences:

These are the characters, that you want to print, but they get skipped because they have special meanings attached to them.
Here is how to do a few formatting in strings in JavaScript.

  • \n - New line
  • \r - Carriage return, In Windows text files, a combination of two characters \r\n represents a new break, while on non-Windows OS it’s just \n. Most Windows software also understands \n.
  • \', \" - Quotes
  • \ - Backslash
  • \t - Tab
  • \b, \f, \v - Backspace, Form Feed, Vertical Tab

Example:

alert( 'I\'m the Kumar!' ); // I'm the Kumar!
Enter fullscreen mode Exit fullscreen mode

String Length:

The length property has the string length:

alert( 'My\n'.length ); // 3
Enter fullscreen mode Exit fullscreen mode

Note:

  • \n is a single β€œspecial” character, so the length is indeed 3

  • In the String, the length is just a property, it is not a function to be called upon strings.

Accessing characters

In JavaScript, To get a character at position pos, use square brackets [pos] or call the method str.at(pos). The first character starts from the zero position.

let str = `Hello`;
// the first character
alert( str[0] ); // H
alert( str.at(-1) ); // o
Enter fullscreen mode Exit fullscreen mode

As usual, the last character is indexed at -1 and so on.

Properties and Important Methods:

1) Strings are immutable
Strings can’t be changed in JavaScript. It is impossible to change a character.
Examples:

let str = 'Hi';
str[0] = 'h'; // error
Enter fullscreen mode Exit fullscreen mode

2) Changing the case
Methods toLowerCase() and toUpperCase() change the case:

alert( 'Kumar'.toUpperCase() ); // KUMAR
alert( 'Kumar'.toLowerCase() ); // kumar
Enter fullscreen mode Exit fullscreen mode

3) Searching a substring:
It can be done using the .indexOf() function
let str = 'Widget with id';

alert( str.indexOf('Widget') ); // 0, because 'Widget' is found at the beginning
alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive
Enter fullscreen mode Exit fullscreen mode

4) Getting a substring
There are 3 methods in JavaScript to get a substring: substring, substr and slice.

str.slice(start, end)
Returns the part of the string from start to (but not including) end.

If there is no second argument, then the slice goes till the end of the string:

let str = "stringify";
alert( str.slice(0, 5) ); // 'strin', the substring from 0 to 5 (not including 5)
alert( str.slice(2) ); // 'ringify', from the 2nd position till the end
Enter fullscreen mode Exit fullscreen mode

str.substring(start, end)
Returns the part of the string between the start and end (not including the end).

This is almost the same as the slice, but it allows the start to be greater than the end (in this case it simply swaps start and end values).

let str = "stringify";
alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring"
Enter fullscreen mode Exit fullscreen mode

str.substr(start [, length])
Returns the part of the string from start, with the given length.

let str = "stringify";
alert( str.substr(2, 4) ); 
Enter fullscreen mode Exit fullscreen mode

Comparing Strings:

Strings are compared character by character in alphabetical order. But there are a few odd things that would happen in the JavaScript world when you compare strings. Let's see a few of them here.

  • A lowercase letter is always greater than the uppercase:
alert( 'a' > 'Z' ); // true
Enter fullscreen mode Exit fullscreen mode
  • Letters with diacritical marks are β€œout of order”:

alert( 'Γ–sterreich' > 'New zealand' ); // true
Here Γ– has a diacritical mark. So it is greater than N, even though N comes before O in alphabetical order. This is because of the higher ASCII values of these special characters.

Here is one more way to compare strings
The call str.localeCompare(str2) returns an integer indicating whether str is less, equal or greater than str2 according to the language rules:

  • Returns a negative number if str is less than str2.
  • Returns a positive number if str is greater than str2.
  • Returns 0 if they are equivalent. For Example:
alert( 'Γ–sterreich'.localeCompare('Zealand') ); // -1
Enter fullscreen mode Exit fullscreen mode

Unicode in JavaScript source code:

In JavaScript, the identifiers and string literals can be expressed in Unicode via a Unicode escape sequence. The general syntax is \uXXXX, where X denotes four hexadecimal digits. For example, the letter o is denoted as β€˜\u006F’ in Unicode.

Example:

var f\u006F\u006F = 'abc';
console.log(foo) //abc
Enter fullscreen mode Exit fullscreen mode

String Concatenation:
How can we end a string article on JavaScript without talking about the great concatenation?

Here is a brief overview of it. The concat() method joins two or more strings. This method does not change the existing strings. It returns a new string.
Syntax:
string.concat(string1, string2, ..., stringX)

Example:

let text1 = "Hello";
let text2 = "world!";
let result = text1.concat(" ", text2);
console.log(result)
//Hello world!
Enter fullscreen mode Exit fullscreen mode

References:

Thank you for your valuable time!!! Happy Coding❀️

Top comments (0)

Join us at DEV Want to join the conversation?
Β 

It's easy! Become a DEV member to follow this post, comment, and more.