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 trialHaardik Gupta
Full Stack JavaScript Techdegree Student 5,459 Pointshelp replace
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 a space, 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've tried a couple of times but can't seem to get the answer
function reformatName(text) {
const rawName = /^(\w+)\s(\w+)$/;
// Type your answer on line 5, below:
const newText = /^(\w+)\s(\w
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>
1 Answer
Steven Parker
231,269 PointsYour regex is incomplete, it's missing the final slash (/).
But you don't need another regex anyway. The "newText" should be a string that contains replacement tokens and symbols to create the output as described by the instructions. Remember that a replacement token is formed by a dollar sign ($) followed by the number representing which order the parenthesized group was found in the regex.
For more details, see the MDN page for "replace".