Home > Software design >  Replace multiple text with specific text
Replace multiple text with specific text

Time:07-22

I wanted to replace the text if the userInput matches the following text

Ok, Ok Got it, Next & Confirm with Yes

Below is the sample code.

const userInput = "Ok Next"

I tried with userInput.replace('ok', 'yes') it works only for Ok.

How I make it work for other words ??

CodePudding user response:

You can pass a regular expression to the first parameter of a String.prototype.replace call, and use the i flag to specify case insensitivity.

For example:

userInput.replace(/ok/i, 'yes')

See here for more information.

CodePudding user response:

Not so clean, but this should make you started.

const watchedInputs = ["Ok", "Ok Got it", "Next", "Confirm", "Yes", "Ok Next"];

function checkUserInput(answer){
  console.log(watchedInputs.includes(answer));
}

checkUserInput("Ok Next");

However, I am just guessing that your approach here isn't solid. You should place a radio button that ask for a YES or NO question.

I cannot imagine all possible user inputs that you cannot catch to replace with a YES.

If you still wants user to type on, this should only as a comment / remarks field.

CodePudding user response:

As @kapitan answered you can use .include to check if the string contain a certain pattern, it may work here but can generate some bug later. What you can do is check each word in isolation using regex. Also, I suggest you to compare input in lowercase or uppercase to support user's input with caps somewhere into. Here your yes value is stocked in response :

const userInput = document.getElementById("userInput");
const output = document.getElementById("output");
const words = ["ok", "ok got it", "next", "confirm", "ok next"];
const wordsRegex = RegExp("\\b("   words.join("|")   ")\\b");
let response;

function check(){
  
  if (wordsRegex.test(userInput.value.toLowerCase())){   //check in lowercase

  response = "yes";
  output.innerHTML = response;
  }
  
  else{
  output.innerHTML = "no";
  }
  
}
<input type="test" id="userInput" placeholder="Type here">
<input type="button" onclick="check()" value="Check">
<p id="output"></p>

  • Related