如何在 JavaScript 中移除非單詞字元?


移除非單詞字元

若要移除非單詞字元,我們需要使用正則表示式。移除非單詞字元的邏輯是,只需用空字串('')代替非單詞字元。

例如

在以下示例中,有許多非單詞字元,並且在它們之間有一個名為“Tutorix 是最好的電子學習平臺”的文字。因此,使用正則表示式,非單詞字元被替換為空字串(''),以便將詞語字元作為輸出。

即時演示

<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

更新於:30-7-2019

283 次瀏覽

Kickstart 您的 職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.