jQuery check if input field has a slash inside of it

Viewed 390

I can't find how to do this. All I see is questions how to check if any value is present not a specific one.

How can I check if a slash is present inside an input field? So for example: value="/" or value="test/test" should both trigger the check.

My input field:

<input class="form-control" id="pagename" type="text" name="pagename" required="">

My jquery:

$("body").on("change","#pagename",function(){
  if($(this).val() == '/'){
    console.log('slash is present');
  }
});

I found something about regex but can't this be done in a simpler way?

3 Answers

Use includes() method to check this.

$("body").on("input", "#pagename", function() {
  if ($(this).val().includes('/')) {
    console.log('slash is present');
  }
});

you can do someting like:

if (your_string.indexOf('/') > -1)
{
     console.log('slash is present');
}

The same way you would check if a string has a '/' you can use as mentioned by carsten. indexOf('/')

$(this).val().indexOf('/') > -1

It's cleaner to make $(this).val() a variable if your going to keep referring to it

val = $(this).val()
val.indexOf('/') > -1 # Will return true if it contain's '/'

Or you can use includes('/')

 val = $(this).val()
 val.includes('/') # Will return True if it includes a '/'

I would say includes is better as it's more readable logically, this will work for all string check's so if you were looking for other characters too. No need to use Regex for simple stuff like this. Regex isn't readable from simply looking at the code.

Related