1

I have an input text where user can write string. I want to have an regular expression in javascript which check if the string starts with three characters FSM. If the user write another string which doesn't start with FSM, this string was automatically remove and give the error message

Example:

  • FSMLERTE True
  • FSMAMAMA True
  • SFMABNE false et remove this content in the input

I do this but it's doesn't work

 var input22Regex= /^[a-z]$/;
 if(inputtxt.value.match(inputRegex)) {
 return true;
 } else {  
 inputtxt.value = '';
 alert("String must start with FSM");
 return false;

any idea ?

H.B.
  • 166,899
  • 29
  • 327
  • 400
obela06
  • 307
  • 5
  • 15

5 Answers5

2

Try the following:

const testRegex = /^FSM/;
function testString(str) {
  if (testRegex.test(str)) {
    return true;
  } else {
    console.log("String must start with FSM");
    return false;
  }
}

console.log(testString('FSMLERTE')); // true
console.log(testString('FSMAMAMA')); //true
console.log(testString('SFMABNE')); // false
1

You can use startsWith

if(inputtxt.value.startsWith('FSM')) {
  return true;
} else {
  inputtxt.value = '';
  alert("String must start with FSM");
  return false;
}
0

I think your regex should look like this

/^FSM(.)*/g
kirsanv43
  • 358
  • 2
  • 13
0

You should use /^FSM[A-Z]*/ which will match all inputs that start with FSM and 0 or more capital letters following it. If you want it to be case-insensitive, you can use this instead: /^FSM[A-Z]*/i

var input22Regex = /^FSM[A-Z]*/;
if (inputtxt.value.match(inputRegex)) {
    return true;
} else {
    inputtxt.value = '';
    alert("String must start with FSM");
    return false;
}
Shahzad
  • 2,033
  • 1
  • 16
  • 23
0

You can try this regex

FSM[a-zA-Z0-9]+

Demo

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jay Parmar
  • 368
  • 2
  • 9
  • It does not anchor to the start of string, so it will give unexpected matches for helloFSMxxx. Also it can't handle spaces, brackets, punctuation symbols, non ASCII symbols, arithmetic operation. – armagedescu Jun 24 '20 at 11:12