String Manipulation and Regular Expressions

In this lesson, we’ll explore string manipulation and regular expressions in JavaScript, drawing comparisons to Java where applicable. As a Java developer, you’ll find some familiar concepts, but JavaScript offers some unique and powerful features for working with strings.

String Methods

JavaScript, like Java, provides a rich set of methods for manipulating strings. Let’s look at some common operations:

// JavaScript
let str = "Hello, World!";

console.log(str.length);  // 13
console.log(str.toUpperCase());  // HELLO, WORLD!
console.log(str.toLowerCase());  // hello, world!
console.log(str.substring(0, 5));  // Hello
console.log(str.replace("World", "JavaScript"));  // Hello, JavaScript!
console.log(str.split(", "));  // ["Hello", "World!"]

These methods should feel familiar to Java developers. However, it’s important to note that strings in JavaScript are immutable, just like in Java. Operations that appear to modify a string actually return a new string.

Template Literals

JavaScript introduces a powerful feature called template literals, which provides an elegant way to create multiline strings and perform string interpolation. This is something not available in Java and is worth exploring in depth.

Template literals are enclosed by backticks (`) instead of single or double quotes:

// JavaScript
let name = "Alice";
let age = 30;

let greeting = `Hello, ${name}!
You are ${age} years old.`;

console.log(greeting);
// Output:
// Hello, Alice!
// You are 30 years old.

The ${expression} syntax allows you to embed expressions directly in your string. This is much more convenient than Java’s string concatenation or String.format() method.

Regular Expressions

Regular expressions in JavaScript are similar to those in Java, but with some syntax differences. In JavaScript, you can create a regular expression using the RegExp constructor or regex literals (/.../):

// JavaScript
// Using the RegExp constructor
let regex1 = new RegExp("pattern", "flags");

// Using regex literal
let regex2 = /pattern/flags;

Let’s look at some examples of using regex for string matching and replacement:

// JavaScript
let text = "The quick brown fox jumps over the lazy dog.";

// Test if a pattern exists in a string
let hasQuick = /quick/.test(text);
console.log(hasQuick);  // true

// Find all occurrences of a pattern
let words = text.match(/\b\w{5}\b/g);
console.log(words);  // ["quick", "brown", "jumps"]

// Replace pattern with new text
let newText = text.replace(/[aeiou]/g, "*");
console.log(newText);  // Th* q**ck br*wn f*x j*mps *v*r th* l*zy d*g.

JavaScript’s regex support is built into the language, unlike Java where you need to import the java.util.regex package.

String Matching and Replacement with Regex

JavaScript provides several methods for working with regular expressions:

  • test(): Returns true if a match is found, false otherwise.
  • exec(): Returns an array of match information or null if no match is found.
  • match(): Returns an array of matches or null if no match is found.
  • replace(): Replaces matched substrings with a replacement string.
  • search(): Returns the index of the first match or -1 if not found.

Here’s an example that demonstrates these methods:

// JavaScript
let sentence = "The rain in Spain stays mainly in the plain";

// test()
console.log(/ain/.test(sentence));  // true

// exec()
console.log(/ain/.exec(sentence));  // ["ain", index: 5, input: "The rain in Spain stays mainly in the plain", groups: undefined]

// match()
console.log(sentence.match(/ain/g));  // ["ain", "ain", "ain"]

// replace()
console.log(sentence.replace(/ain/g, "ANE"));  // "The rANE in SpANE stays mANEly in the plANE"

// search()
console.log(sentence.search(/Spain/));  // 12

These methods provide powerful tools for string manipulation and pattern matching that can greatly simplify many text processing tasks.

Conclusion

In this lesson, we’ve explored string manipulation and regular expressions in JavaScript. We’ve seen how JavaScript’s string methods are similar to Java’s, but with the addition of powerful features like template literals. We’ve also looked at how regular expressions are integrated into the language, providing robust pattern matching and replacement capabilities.

In the next lesson, we’ll dive into object-oriented programming in JavaScript. We’ll explore how JavaScript’s prototypal inheritance differs from Java’s class-based inheritance, and how the ES6 class syntax provides a more familiar interface for Java developers. Get ready to see how JavaScript handles concepts like classes, inheritance, and encapsulation!