简体   繁体   中英

how to check whether any special character is present in a particular string

I want to remove the '<' '>' from the string so i used the script

<html>
<body>

 <script>
  var f = ((/(<script>)/i).exec("hello<") != null);
  alert("ok"+f);

  document.write("<br>Value:" +f);

 </script>
</body>
</html>

But i'm getting the variant f value as null..

Could you please help me.if there is any issue with the code.

I hope this will help

if("hello<".indexOf('<') != -1){
     var f = "hello<".replace('<','');
     alert("ok "+f);   
}​​​​​​​​​​​​​​​

You can you JavaScript regular expressions to achieve this.

"<script>".replace(/<|>/ig, "");
outputs: "script"
  var f = ('<script>'.replace(/<|>/g, ''));
  alert("ok"+f);

  document.write("<br>Value:" +f);

You can use .test method:

​var originalString = '<script>',
    r = originalString.test(/<|>/g, ''); // returns true or false

if (r === true) {
  //whatever you wanna do if you have special characters in 
  // your string
} else {
  // no special chars - all clean!
}

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