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!

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 trial

JavaScript Regular Expressions in JavaScript Reformatting User Input Reformatting Text

help 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 => {
  reformatted.textContent = reformatName(input.value);
<!DOCTYPE html>

    <title>DOM Manipulation</title>
<link rel="stylesheet" href="style.css" />

    <div id="content">
            <label for="name">Enter your first and last name, please.</label>
            <br />
            <input type="text" id="name" name="name">
            <button type="submit">Reformat</button>
            <h2>Reformatted name:</h2>
                <p id="reformatted"></p>
    <script src="app.js"></script>


1 Answer

Steven Parker
Steven Parker
227,114 Points

Your 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".