Home > front end >  Regular Expression To Make Sure All The Words In A String Only Have Letters
Regular Expression To Make Sure All The Words In A String Only Have Letters

Time:11-12

I'm coding a To-Do List in Visual Studio Code and I want to make sure all the items I add to the To-Do List are viable and don't have numbers. I'm fine with having a one word item but I also need it to check more than one word items for numbers. The regex expression I've been running unsuccessfully is:

const pattern = /\b[a-zA-Z]{0,}\b/;

I am new to Javascript and I don't understand regular expressions anymore than the most basic components. Help is much needed :)

Here is the HTML code:

<div >

        <header >

            <h1 >Todo List</h1>

            <form >

                <input  type="text" name="search" placeholder="search todos" />
        
            </form>

        </header>

      <ul >

          <li >
              
              <span>Take out trash</span>
          
              <i ></i>
        
          </li>

          <li >
              
              <span>Vacuum</span>
          
              <i ></i>
        
          </li>

          <li >
              
            <span>Homework</span>
        
            <i ></i>
      
          </li>

      </ul>

      <form >

          <label >Add a new todo...</label>
          
          <input  type="text" name="add"/>

      </form>

    </div>

Here is my Javascript code:


const pattern = /\b[a-zA-Z]{1,}\b/;

addForm.addEventListener('submit', e => {

    e.preventDefault();

    const todo = e.target.add.value.trim();

    if (pattern.test(todo)) {

        generateTemplate(todo);

        addForm.reset();

    }

});

P.S. I've been using Regex101 to test my expressions I hope this is ok.

I tried the regular expression:

/\b[a-zA-Z]{0,}\b/;

and expected for it to be able to test all the words and return false if there were numbers in any one of them. What resulted was it just matched one word without numbers in the String and called it a day. I need it to check every word. (I'm aware I could use a ForEach loop but a simple expression would be preferable.

CodePudding user response:

For my answer, I'm running the regular expression in the input event handler. So that it cleans the input as the user types it in.

This replaces all non letters and spaces then replaces all multiple spaces in a row to clean it up.

e.target.value = e.target.value.replace(/[^a-zA-Z\s]/g,'').replace(/ /g, ' ')

UPDATE Updated to use match on the press of the submit button instead of replacing.

let inputField = document.querySelector("[name='add']"),
  btn = document.querySelector(".btn-add")

btn.addEventListener("click", () => {
  if (inputField.value.match(/[^a-zA-Z\s]/g, '')) {
    console.log("NOT VALID");
  } else {
    console.log("ADD!");
  }
});
<input  type="text" name="add" />
<button  type="button">Add To List</button>

  • Related