Back to JavaScript
2026-01-158 min read

Swift Strings (JavaScript)

Learn Swift Strings (JavaScript) step by step with clear examples and exercises.

Why This Matters

In this extensive guide on Swift Strings in JavaScript, we delve deep into understanding strings and their manipulation in web development. Strings are crucial for creating dynamic content, parsing user input, and communicating with APIs. While Swift has a dedicated String type, JavaScript uses the more flexible String object, which we'll explore in this lesson. Mastering string manipulation is key to writing cleaner, more efficient code and tackling real-world programming challenges.

Prerequisites

Before diving into Swift Strings in JavaScript, it is essential to have a good understanding of:

  1. Basic JavaScript concepts such as variables, data types, functions, and operators
  2. DOM manipulation using methods like document.getElementById() and event handling
  3. Familiarity with ES6 features like arrow functions, template literals, and destructuring assignments
  4. Understanding of regular expressions to perform more complex string operations
  5. Knowledge of object-oriented programming concepts, as strings in JavaScript are objects
  6. Familiarity with common data structures such as arrays and maps
  7. Understanding of event loop and call stack in JavaScript
  8. Basic understanding of asynchronous programming and promises

Core Concept

In JavaScript, a string is an object that represents a sequence of characters. Strings are created by enclosing text within single quotes (') or double quotes ("). Here's a simple example:

let myString = 'Hello, World!';

String Methods

JavaScript provides numerous methods for manipulating strings. Some of the most commonly used ones include:

  • length: returns the number of characters in the string
  • substring(), slice(), and substr(): extract a portion of the string
  • indexOf(), lastIndexOf(), and search(): find the position of a specified character or substring
  • replace(): replace occurrences of a specified pattern with another string
  • trim(), trimStart(), and trimEnd(): remove whitespace from the beginning, end, or both sides of a string
  • charAt(): returns the character at a specific index
  • split(): splits a string into an array based on a specified delimiter
  • concat(): concatenates two or more strings
  • toLowerCase() and toUpperCase(): convert all characters in the string to lowercase or uppercase, respectively

Template Literals

Introduced in ES6, template literals provide an easier way to create multi-line strings and perform string interpolation. Here's an example using a template literal:

let name = 'John';
let greeting = `Hello, ${name}! How are you today?`;
console.log(greeting); // Output: Hello, John! How are you today?

Regular Expressions

Regular expressions (regex) allow for more complex string operations by defining patterns to match within strings. JavaScript provides built-in support for regex with the RegExp constructor and various methods like test(), exec(), and match().

Worked Example

Let's create a simple web page that takes user input, validates it using a regular expression, counts the number of vowels, and displays the length of their entered string.

  1. Create an HTML file (index.html) with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swift Strings in JavaScript</title>
</head>
<body>
<h1>String Analysis Tool</h1>
<input id="userInput" type="text">
<button onclick="analyzeString()">Analyze String</button>
<p id="result"></p>

<script src="app.js"></script>
</body>
</html>
  1. Create a JavaScript file (app.js) with the following content:
function analyzeString() {
const userInput = document.getElementById('userInput').value;
const regex = /^[a-zA-Z0-9 ]+$/; // Regular expression for validating alphanumeric characters and spaces

if (regex.test(userInput)) {
const vowelCount = countVowels(userInput);
const resultElement = document.getElementById('result');
resultElement.textContent = `The length of your entered string is ${userInput.length}. There are ${vowelCount} vowels in the string.`;
} else {
alert("Please enter a valid alphanumeric string.");
}
}

function countVowels(str) {
const vowels = ['a', 'e', 'i', 'o', 'u'];
let count = 0;
for (let i = 0; i < str.length; i++) {
if (vowels.includes(str[i].toLowerCase())) {
count++;
}
}
return count;
}

Common Mistakes

  1. Forgetting to enclose strings in quotes:
let myString = Hello, World! // Syntax error: Unexpected identifier

Solution: Enclose the string in either single or double quotes.

  1. Using == instead of === for string comparison:
let str1 = 'Hello';
let str2 = 'hello';
if (str1 == str2) { // This will evaluate to true, which is incorrect
console.log('The strings are equal.');
}

Solution: Use === for strict equality comparison between strings.

  1. Using substring() with incorrect arguments:
let myString = 'Hello, World!';
let substringResult = myString.substring(5); // Output: 'World!' (excludes the comma)

Solution: Use slice() or specify the start and end indices correctly when using substring().

  1. Not considering case sensitivity in string comparisons:
let str1 = 'Hello';
let str2 = 'hello';
if (str1 === str2) { // This will evaluate to false, because JavaScript is case-sensitive
console.log('The strings are equal.');
}

Solution: Use toLowerCase() or toUpperCase() methods to convert strings to the same case before comparison.

  1. Using += for concatenation instead of the + operator:
let str1 = 'Hello';
let str2 = 'World';
let concatenatedStr = str1 += str2; // Output: 'HelloWorld', but `str1` is modified

Solution: Use the + operator for concatenation, or use the assignment operator (=) if you want to modify the original string.

  1. Assuming that JavaScript automatically converts numbers and strings when performing arithmetic operations:
let num = 5;
let str = '3';
let result = num + str; // Output: '53', because JavaScript converted '3' to a number

Solution: Use the parseInt() or parseFloat() functions if you want to perform arithmetic operations on strings that represent numbers.

  1. Not understanding the difference between primitive and reference types in JavaScript, which can lead to unexpected behavior when manipulating strings:
let str1 = 'Hello';
let str2 = str1;
str2 += ', World!'; // Both `str1` and `str2` now have the value 'Hello, World!'

Solution: Understand that strings in JavaScript are reference types, so modifying one string affects all variables referring to that same object. If you want to create a new string with modified content, use the assignment operator (=) or concatenation (+).

Practice Questions

  1. Write a JavaScript function that capitalizes the first letter of a given string and leaves the rest of the letters in lowercase.
  2. Create a script that reverses the order of characters in a given string without using any built-in methods.
  3. Write a program that checks if a given string is a palindrome (reads the same forwards and backwards).
  4. Write a regular expression to validate an email address with at least one digit.
  5. Write a function that removes all duplicate words from a given string, ensuring the order of words remains the same as in the original string.
  6. Write a function that finds and replaces all occurrences of a specified word in a given string with another word, but only if the replaced word is longer than the original word.
  7. Write a function that checks if a given string is a valid password (at least 8 characters long, contains at least one digit, one uppercase letter, and one lowercase letter).

FAQ

  1. Why can't I use the += operator to concatenate strings in JavaScript?

In JavaScript, the += operator performs arithmetic addition and then assignment. When you try to concatenate strings using this operator, it will first convert one of the operands (if not already a string) into a string, which can lead to unexpected results. Instead, use the + operator for concatenation.

  1. What is the difference between substring(), slice(), and substr() in JavaScript?

All three methods extract a portion of a string, but they differ in their syntax:

  • substring() takes two arguments: the starting index and (optionally) the ending index.
  • slice() also accepts three arguments: the starting index, the ending index, and an optional step value.
  • substr() takes two arguments: the starting index and the number of characters to extract.
  1. How can I remove all whitespace from a string in JavaScript?

Use the replace() method with a regular expression that matches all whitespace characters (spaces, tabs, line breaks, etc.). Here's an example:

let myString = ' Hello, World! ';
let trimmedString = myString.replace(/\s+/g, ''); // Output: 'Hello,World!'
  1. How can I find the position of a specified character in a string using JavaScript?

Use the indexOf() method to find the index of the first occurrence of a specified character within a string. If you need to find all occurrences, use the match() method with a regular expression that matches the character. Here's an example:

let myString = 'Hello, World!';
let position = myString.indexOf('l'); // Output: 2 (the index of the first occurrence of 'l')
let allPositions = myString.match(/l/g); // Output: [ 'l', 2, 'l', 5 ] (all positions of 'l' in the string)
  1. How can I count the number of occurrences of a specified substring within a string using JavaScript?

Use the match() method with a regular expression that matches the substring, and use the length property of the resulting array to find the number of occurrences. Here's an example:

let myString = 'Hello, World! Hello again, World!';
let count = (myString.match(/World!/g) || []).length; // Output: 2 (the number of occurrences of 'World!')
  1. How can I find the last occurrence of a specified character in a string using JavaScript?

Use the lastIndexOf() method to find the index of the last occurrence of a specified character within a string. Here's an example:

let myString = 'Hello, World!';
let position = myString.lastIndexOf('l'); // Output: 5 (the index of the last occurrence of 'l')
  1. How can I split a string into an array based on a specified delimiter using JavaScript?

Use the split() method with the desired delimiter as its argument. Here's an example:

let myString = 'apple,banana,orange';
let fruitsArray = myString.split(','); // Output: ['apple', 'banana', 'orange']
  1. How can I convert a string to uppercase or lowercase using JavaScript?

Use the toUpperCase() or toLowerCase() method to convert all characters in the string to uppercase or lowercase, respectively. Here's an example:

let myString = 'Hello, World!';
let upperCaseString = myString.toUpperCase(); // Output: 'HELLO, WORLD!'
let lowerCaseString = myString.toLowerCase(); // Output: 'hello, world!'
  1. How can I replace all occurrences of a specified substring within a string using JavaScript?

Use the replace() method with the desired replacement string and a regular expression that matches the substring to be replaced. Here's an example:

let myString = 'Hello, World!';
let newString = my
Swift Strings (JavaScript) | JavaScript | XQA Learn