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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let code_txt = "Codeunderscored String";
let length = code_txt.length;
console.log(length)</pre>
</div>

String Parts Extraction

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>slice(start, end)
substring(start, end)
substr(start, length)</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let computer_companies = "IBM, Microsoft, Google, Uber";
let sliced_part = computer_companies.slice(4, 8);
console.log(sliced_part)</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let computer_companies = "IBM, Microsoft, Google, Uber";
let sliced_part = computer_companies.slice(-12, -6);
console.log(sliced_part)</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let sliced_part = computer_companies.slice(7);
console.log(sliced_part)</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let sliced_part = computer_companies.slice(-12);
console.log(sliced_part)</pre>
</div>

String substring() in JavaScript

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let computer_companies = "IBM, Microsoft, Google, Uber";
let sliced_part = computer_companies.substring(4, 8);
console.log(sliced_part)</pre>
</div>

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.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>et computer_companies = "IBM, Microsoft, Google, Uber";
let sliced_part = computer_companies.substr(7, 6);
console.log(sliced_part)</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let computer_companies = "IBM, Microsoft, Google, Uber";
let sliced_part = computer_companies .substr(5);
console.log(sliced_part)</pre>
</div>

String Content Replacement

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let language_text = "Coding in Python is core at Codeunderscored!";
let final_text = language_text.replace("Python", "JavaScript");
console.log(final_text)</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let language_text = "Codeunderscored is famous for Python and Python!";
let final_text = language_text.replace("Python", "JavaScript");
console.log(final_text)</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let language_text = "Codeunderscored is famous for Python";
let final_text = text.replace("PYTHON", "JavaScript");
console.log(final_text )</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let language_text = "Codeunderscored is famous for Python";
let final_text = text.replace(/PYTHON/i, "JavaScript");
console.log(final_text )</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let language_text = "Codeunderscored is famous for Python and Python";
let final_text = text.replace(/Python/g, "JavaScript");
console.log(final_text )</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>et statement_lowercase = "welcome to codeunderscored!";
let statement_uppercase = statement_lowercase.toUpperCase();
console.log(statement_uppercase)</pre>
</div>

Using toLowerCase() JavaScript string

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let statement = "Welcome to Codeunderscored!";
let string_lowercase = statement.toLowerCase();
console.log(string_lowercase)</pre>
</div>

concat() String in JavaScript ()

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>first_statement = "Programming in ";
let second_statement = "JavaScript is wonderful";
let final_statement = first_statement .concat(" ", second_statement);
console.log(final_statement)</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>finalStatementOne = "Programming in" + " " + "JavaScript is wonderful!";
finalSstatementTwo = "Programming in".concat(" ", "JavaScript is wonderful!");

console.log(finalStatementOne)
console.log(finalSstatementTwo)</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let txt_to_trim = " JavaScript is wonderful! ";
let trim_text = txt_to_trim.trim();
console.log(trim_text)</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let textVal = "5";
let paddedText = textVal.padStart(4,0);
console.log(paddedText)</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let textVal = "5";
let paddedText = textVal.padEnd(4,0);

console.log(paddedText)</pre>
</div>

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):

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>et originalString = "WELCOME TO CODEUNDERSCORED";
let extractedChar = originalString.charAt(0);
console.log(extractedChar)</pre>
</div>

String charCodeAt() in JavaScript

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let originalString = "WELCOME TO CODEUNDERSCORED";
let extractedChar = originalString.charCodeAt(0);
console.log(extractedChar)</pre>
</div>

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 []:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let originalString = "WELCOME TO CODEUNDERSCORED";
let extractedChar = originalString[0];
console.log(extractedChar)</pre>
</div>

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!.
<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let originalString = "WELCOME TO CODEUNDERSCORED";
originalString[0] = "A";
console.log(originalString)</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>originalString.split(",") // Split on commas
originalString.split(" ") // Split on spaces
originalString.split("|") // Split on pipe</pre>
</div>

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 “:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>originalString.split("")</pre>
</div>

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *