简体   繁体   中英

how can i find only the full word and not just part of it in regex?

how can i use match() method or any other method to find only the full word itself. not just part of it for example if the user will enter the word sixty it will not execute the if Statements with the match() method,i want that only if the user will enter the word six itself it will execute the if statements

  var inputNum = prompt("Please enter a number between 50 and 100:");

  if (isNaN(inputNum)) {
  if (inputNum.match(/one|two|three|four|five|six|seven|eight|nine|ten/)) {
  alert("While this is a number, it's not really a number to me.");
  } else {
  alert(inputNum + " doesn't appear to be a number.");
  }
  }



 

Use test instead like:

var inputNum = "one";

let result = /one|two|three|four|five|six|seven|eight|nine|ten/.test(inputNum);
console.log("one", result);

Here is a full demo

 var inputNum = prompt("Please enter a number between 50 and 100:"); let result = /one|two|three|four|five|six|seven|eight|nine|ten/.test(inputNum); console.log(inputNum," ",result);

You just need to add ^ in the beginning and $ in the end

  • ^ indicates the beginning of the string.
  • $ indicates the end of the string.

This will ensure that your word will exactly match six and not sixty . If you type sixty else block will execute and on typing six if block, as you wanted.

 var inputNum = prompt("Please enter a number between 50 and 100:"); if (isNaN(inputNum)) { if (inputNum.match(/^(one|two|three|four|five|six|seven|eight|nine|ten)$/)) { alert("While this is a number, it's not really a number to me."); } else { alert(inputNum + " doesn't appear to be a number."); } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM