Home Web DevelopmentJavaScript Strings in JavaScript

Strings in JavaScript

A sequence of characters is represented and manipulated using the String object. You can use Strings to store data that can be represented as text. Checking the length of a string, building and concatenating it with the plus and += string operators, checking for substrings’ existence or location with the indexOf() method, and extracting substrings with the substring() method are some of the most common operations on strings.

The default attributes and methods in a JavaScript string are applicable for various applications. The latter is inclusive of primitive and String objects.

String Properties and Methods

Values that don’t have properties or methods, such as “Mark John,” are considered primitive. The reason for this is the latter are not objects. However, primitive values do use JavaScript methods and properties because JavaScript interprets primitive values as objects when executing methods and properties.

String Length in JavaScript

The length attribute returns the string’s length:

let code_txt = "Codeunderscored String";
let length = code_txt.length;
console.log(length)

String Parts Extraction

There are three ways to extract a portion of a string:

slice(start, end)
substring(start, end)
substr(start, length)

String slice() in JavaScript

slice() takes a string’s section and returns it as a new string. The technique accepts the start and end positions though the end is not included. This example cuts a section of a string from position 4 to position 8 as follows:

let computer_companies = "IBM, Microsoft, Google, Uber";
let sliced_part = computer_companies.slice(4, 8);
console.log(sliced_part)

JavaScript starts counting at zero. As it turns out, the number zero is in the first position while the number one is in second place. In addition, the position is counted from the end of the String if a parameter is negative. This example takes a section of a string from position -12 to position -6 and slices it out:

let computer_companies = "IBM, Microsoft, Google, Uber";
let sliced_part = computer_companies.slice(-12, -6);
console.log(sliced_part)

The method task is to slice out the rest of the String if the second parameter is omitted:

let sliced_part = computer_companies.slice(7);
console.log(sliced_part)

or, the result is as follows when counting from the end:

let sliced_part = computer_companies.slice(-12);
console.log(sliced_part)

String substring() in JavaScript

String substring() in JavaScript is equivalent to slice() in JavaScript . Substring(), on the other hand, does not take negative indexes.

let computer_companies = "IBM, Microsoft, Google, Uber";
let sliced_part = computer_companies.substring(4, 8);
console.log(sliced_part)

Substring() is responsible for slicing out the rest of the String if omitted the second parameter.

String substr() in JavaScript

slice() is comparable to substr() . On the other hand, the second option sets the length of the extracted section.

et computer_companies = "IBM, Microsoft, Google, Uber";
let sliced_part = computer_companies.substr(7, 6);
console.log(sliced_part)

Substr() is tasked with slicing out the rest of the String if omitted the second parameter.

let computer_companies = "IBM, Microsoft, Google, Uber";
let sliced_part = computer_companies .substr(5);
console.log(sliced_part)

String Content Replacement

The replace() method in a string substitutes a specified value with another one:

let language_text = "Coding in Python is core at Codeunderscored!";
let final_text = language_text.replace("Python", "JavaScript");
console.log(final_text)

Key pointers to note about the replace() method:

  • The replace() method does not affect the String on which it is invoked.
  • The replace() method returns a string with a new one.
  • Only the first match is replaced using the replace() method.
  • On the flip side, if you choose to replace all matches, then use a regular expression with the /g flag set. Please see the samples below.
  • The replace() method is responsible for replacing only the first match by default.

Example showing the default replace() method

let language_text = "Codeunderscored is famous for Python and Python!";
let final_text = language_text.replace("Python", "JavaScript");
console.log(final_text)

The replace() method is case sensitive by default. It is not possible to write PYTHON in upper case:

let language_text = "Codeunderscored is famous for Python";
let final_text = text.replace("PYTHON", "JavaScript");
console.log(final_text )

Use a regular expression with the /i flag (insensitive) to replace case insensitive:

let language_text = "Codeunderscored is famous for Python";
let final_text = text.replace(/PYTHON/i, "JavaScript");
console.log(final_text )

Regular expressions are written without the need for quotation marks. The /g flag is used with regular expressions to indicate a global match to replace all matches:

let language_text = "Codeunderscored is famous for Python and Python";
let final_text = text.replace(/Python/g, "JavaScript");
console.log(final_text )

Upper and Lower Case Conversion

toUpperCase() is a function that converts a string to the upper case. On the other hand, to convert a string to lower case, use toLowerCase().

Using toUpperCase() JavaScript string

et statement_lowercase = "welcome to codeunderscored!";
let statement_uppercase = statement_lowercase.toUpperCase();
console.log(statement_uppercase)

Using toLowerCase() JavaScript string

let statement = "Welcome to Codeunderscored!";
let string_lowercase = statement.toLowerCase();
console.log(string_lowercase)

concat() String in JavaScript ()

concat() is a function that joins two or more strings:

first_statement = "Programming in ";
let second_statement = "JavaScript is wonderful";
let final_statement = first_statement .concat(" ", second_statement);
console.log(final_statement)

Opt to use the concat() function as opposed to using the plus operator. These two lines accomplish the same thing:

finalStatementOne = "Programming in" + " " + "JavaScript is wonderful!";
finalSstatementTwo = "Programming in".concat(" ", "JavaScript is wonderful!");

console.log(finalStatementOne)
console.log(finalSstatementTwo)

All string functions return a new string. Essentially, they do not interfere with the original String in any way. Formally, it is stated: Strings are immutable, which means they can’t be modified but can only be substituted.

String trim() in JavaScript

Trim eliminates whitespace from both sides of a string with this method:

let txt_to_trim = " JavaScript is wonderful! ";
let trim_text = txt_to_trim.trim();
console.log(trim_text)

String Padding in JavaScript

To support padding at the beginning and end of a string, ECMAScript 2017 introduces two String methods: padStart and padEnd.

String padStart() in JavaScript

let textVal = "5";
let paddedText = textVal.padStart(4,0);
console.log(paddedText)

padStart() is a new functionality in ECMAScript 2017. It’s compatible with all contemporary browsers. However, in Internet Explorer, padStart() is not supported.

String padEnd() in JavaScript

let textVal = "5";
let paddedText = textVal.padEnd(4,0);

console.log(paddedText)

padEnd() is a new functionality in ECMAScript 2017. It’s compatible with all contemporary browsers. Unfortunately, in Internet Explorer, padEnd() is not supported.

String Characters Extraction

String characters can be extracted using one of three methods:

  • charAt(position)
  • charCodeAt(position)
  • Property access [ ]
  • JavaScript String charAt()

The charAt() method returns the character in a string at a given index (position):

et originalString = "WELCOME TO CODEUNDERSCORED";
let extractedChar = originalString.charAt(0);
console.log(extractedChar)

String charCodeAt() in JavaScript

The characters’ unicode at a particular index in a string is returned by the charCodeAt() method:

let originalString = "WELCOME TO CODEUNDERSCORED";
let extractedChar = originalString.charCodeAt(0);
console.log(extractedChar)

A UTF-16 code refers to an integer between 0 and 65535 and is returned by this procedure.

Property Access

Property Access on strings, ECMAScript 5 (2009) supports property access []:

let originalString = "WELCOME TO CODEUNDERSCORED";
let extractedChar = originalString[0];
console.log(extractedChar)

Property access may be a little unpredictable:

  • It transforms strings into arrays (but they are not)
  • [] returns undefined if no character is found, while charAt() returns an empty string.
  • It is a read-only document. There is no problem when str[0] = “A” is used but it does not work!.
let originalString = "WELCOME TO CODEUNDERSCORED";
originalString[0] = "A";
console.log(originalString)

Converting a String to an Array

It is vital to have the option to convert a string to an array if you want to use it.

split() in JavaScript String

The split() method can be used to convert a string to an array:

originalString.split(",") // Split on commas
originalString.split(" ") // Split on spaces
originalString.split("|") // Split on pipe

If the separator isn’t specified, the returned array will have the entire String at index [0]. The resultant array that is returned will be an array of single characters if the separator is “:

originalString.split("")

You may also like

Leave a Comment