Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีลบ Non-word Characters ใน JavaScript

การลบ Non-word Characters

ลบ non-word characters ใช้ Regular Expressions ตรรกะคือแทนที่ non-word characters ด้วย '' (ว่าง)

ตัวอย่าง

สตริงมี non-word characters หลายตัว ระหว่างมีข้อความ "Tutorix is the best e-learning platform" ใช้ regex แทนที่ non-word ด้วย '' ได้ข้อความที่ต้องการ

<html> <body> <script type="text/javascript"> 
    function remNonWord(string) { 
        if ((string === null) || (string === '')) return false; 
        else string = string.toString(); 
        var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; 
        return string.replace(PATTERN, ''); 
    } 
    document.write(remNonWord('Tutorix is the ~!@^&";\'/?>#$%*()+`={}[]|\\:<.,best e-learning platform')); 
</script> </body> </html>

ผลลัพธ์

Tutorix is the best e-learning platform