CodingNic

Strings and Regular Expressions

Strings and Regular Expressions Exercises

Strings and Regular Expressions 40 min read

Strings and Regular Expressions Exercises

Objectives

This chapter introduces no new concepts. It’s a chance to put string methods, template literals, and regular expressions into practice with real code.

Part I: String Methods

  1. Given const city = " Nairobi ";, trim it and log the trimmed string’s length. Expected: "Nairobi", length 7.
  2. Given const shout = "javascript is fun";, log it in uppercase. Expected: "JAVASCRIPT IS FUN".
  3. Given const path = "user/settings/profile";, use .includes() to check whether it contains "settings". Expected: true.
  4. Given const sentence = "The meeting is at 3pm";, use .indexOf() to find the position where "3pm" starts. Expected: 18.
  5. Given const word = "fundamentals";, use .slice() to extract just "mental" from it. Expected: "mental".
  6. Given const tags = "javascript,web,beginner";, split it into an array of three strings. Expected: [ 'javascript', 'web', 'beginner' ].
  7. Given const message = "I like cats";, replace "cats" with "dogs". Expected: "I like dogs".

Part II: Template Literals

  1. Given const user = "Sam"; and const score = 87;, use a template literal to log "Sam scored 87 points.".
  2. Write a multi-line template literal for a two-item receipt, with each item and its price on its own line. Build it from variables for the item names and prices. Expected output, across four lines: Item: Notebook, Price: 5, Item: Pen, Price: 1.

Part III: Regular Expressions

  1. Write a pattern that matches at least one digit anywhere in a string. Test it against "room42" (expected: true) and "room" (expected: false).
  2. Write a pattern, using ^, that checks whether a string starts with "Error". Test it against "Error: file not found" (expected: true) and "Fatal Error" (expected: false).
  3. Given const raw = "Priya just logged in";, use .replace() with a regex to collapse every run of extra spaces down to one. Expected: "Priya just logged in".
  4. Given const record = "id:482";, write a pattern with two groups, one for the label and one for the number, and log both captured groups separately. Expected: "id" and "482".
  5. Write a pattern that matches a string of exactly three digits, anchored so nothing extra is allowed before or after. Test it against "482" (expected: true), "48" (expected: false), and "4820" (expected: false).

Recap

You can now clean up, search, and reshape text with string methods, build readable strings with template literals instead of + concatenation, and write and use simple regular expressions to test, extract, and replace patterns in text.

Next module: object-oriented programming, where you’ll design your own classes.