Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBrian Foley
8,440 PointsRegExp challenge question stuck
I'm kind of swinging in the dark here. Here's the challenge:
This challenge contains a form that will accept a first and last name (separated with a space), and display the last name first, then a comma, then the first name. Your challenge is to create a variable newText, and assign a replacement string to that variable. Be careful to match the exact variable name, because that's what is passed into replace(). You'll also need to reference the values captured by the parentheses in the regex.
I went with const newText = '$2 $1'; but that's not it. Any ideas? Thanks for the help!
function reformatName(text) {
const rawName = /^(\w+)\s(\w+)$/;
// Type your answer on line 5, below:
const newText = '$2 $1';
return text.replace(rawName, newText);
}
const form = document.querySelector("form");
const input = form.querySelector("input");
const reformatted = document.getElementById("reformatted");
form.addEventListener("submit", e => {
e.preventDefault();
reformatted.textContent = reformatName(input.value);
});
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation</title>
</head>
<link rel="stylesheet" href="style.css" />
<body>
<div id="content">
<form>
<label for="name">Enter your first and last name, please.</label>
<br />
<input type="text" id="name" name="name">
<button type="submit">Reformat</button>
</form>
<div>
<h2>Reformatted name:</h2>
<p id="reformatted"></p>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
5 Answers
Steven Parker
231,236 PointsYou're close, but you overlooked part of the instructions, which said, "display the last name first, then a comma, then the first name".
You got the names in the right order, but you forgot the comma.
riannonriannon
12,161 PointsBrain is right. this worked for me:
const newText = "$2 , $1";
Mourad Gharsalli
9,065 PointsI tried it mine still does not work what's the problem const newText = '$2,$1' ;
Steven Parker
231,236 PointsThe challenge does want to see a space after the comma.
tjeiosajfdksl
Courses Plus Student 8,981 PointsI tried it mine still does not work const newText = "$2 , $1"; \
what is wrong?
Brian Foley
8,440 PointsHi James, delete that space after the 2 :)
L Haney
Front End Web Development Techdegree Student 10,263 PointsThis is what worked for me:
let newText = '$2, $1';
Make sure there is a space only after the comma.