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
- Given
const city = " Nairobi ";, trim it and log the trimmed string’s length. Expected:"Nairobi", length7. - Given
const shout = "javascript is fun";, log it in uppercase. Expected:"JAVASCRIPT IS FUN". - Given
const path = "user/settings/profile";, use.includes()to check whether it contains"settings". Expected:true. - Given
const sentence = "The meeting is at 3pm";, use.indexOf()to find the position where"3pm"starts. Expected:18. - Given
const word = "fundamentals";, use.slice()to extract just"mental"from it. Expected:"mental". - Given
const tags = "javascript,web,beginner";, split it into an array of three strings. Expected:[ 'javascript', 'web', 'beginner' ]. - Given
const message = "I like cats";, replace"cats"with"dogs". Expected:"I like dogs".
Part II: Template Literals
- Given
const user = "Sam";andconst score = 87;, use a template literal to log"Sam scored 87 points.". - 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
- Write a pattern that matches at least one digit anywhere in a string. Test it against
"room42"(expected:true) and"room"(expected:false). - 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). - 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". - 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". - 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.