Home > Back-end >  Display all special characters found in a value
Display all special characters found in a value

Time:07-26

I have an input element and on click of a button I check if its value contains a set of special characters and return a Boolean and it works fine. What I am trying to achieve is once the Boolean is returned if any special character is found in the value I want to display those special characters in a p tag. How can I achieve this? Thanks in advance.

const format = /[ `!@#$%^&*_ -=\[\]{};':"\\|<>\/?~]/
const value = $('input').val()
$('button').on('click', function() {
  if (format.test(value) == true) {
    //something like this
    $('p').html(the found special character   'not allowed')
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<button>click me</button>
<p></p>

CodePudding user response:

If you are looking to find non alphanumeric characters, I would use /[^A-Z0-9,]/ig instead. Also using match allows you to see if results exist and displaying them

const format = /[^A-Z0-9,]/ig

$('button').on('click', function() {
  $('p').html("")
  const value = $('input').val()
  const results = value.match(format)
  if (results) {
    $('p').html(results.join(',')   ' is not allowed')
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<button>click me</button>
<p></p>

CodePudding user response:

You can use String.prototype.match function instead of Regexp.prototype.test. Match function will give you information about result and if you want to see all results you have to use g flag.

It will return array which contains all matches and it will return null if there is not any match.

const format = /[ `!@#$%^&*_ -=\[\]{};':"\\|<>\/?~]/g
$('button').on('click', function() {
  const value = $('input').val()
  const result = value.match(format)
  if (result) {
    $('p').html(result.join(',')   ' is not allowed')
  }
})

More information about match - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

Also you have to put code of getting value of input inside onclick event, because you want to get value of input when you clicked on button not when script executed.

  • Related