Filtering out inappropriate language using special characters

Utilizing https://www.npmjs.com/package/bad-words, I have created a regex to filter out special characters.

const Filter = require('bad-words');
const badWordsFilter = new Filter({replaceRegex:  /[A-Za-z0-9öÖÇ窺ĞğİıÜü_]/g});
badWordsFilter.addWords(['badword', 'şğ'])

The filtering works when the word does not contain Turkish characters. However, when Turkish characters like ş or ğ are included, it does not filter them out.

Is there an issue with my regex?

I came across this code in the documentation:

var filter = new Filter({ regex: /\*|\.|$/gi });
var filter = new Filter({ replaceRegex:  /[A-Za-z0-9가-힣_]/g }); 
//multilingual support for word filtering

Answer №1

It appears that there might be an encoding issue with your regex, as it seems to work fine outside of your application. You can check it out here: https://regex101.com/r/VpItfH/3/.

To potentially solve this problem, try encoding the characters in your regex within your application:

You can view the result of the encoded regex here: https://regex101.com/r/VpItfH/4/


Further Details

If you test the encoded regex in a PCRE regex engine, it should work (https://regex101.com/r/VpItfH/5):

/[A-Za-z0-9\x{f6}\x{d6}\x{c7}\x{e7}\x{15e}\x{15f}\x{11e}\x{11f}\x{130}\x{131}\x{dc}\x{fc}_]/g

However, if you are using a JavaScript regex engine, the { and } may cause issues with the Unicode characters. In such cases, simply remove them and replace \x with \u0 if needed. For example, \x{15e} can be written as \u015e

By following these steps, you should be able to achieve the same results as when using

/[A-Za-z0-9öÖÇ窺ĞğİıÜü_]/g
.

Note: To obtain the unicode representation of a character, you can use "Ğ".charCodeAt(0).toString(16); and then add either \x or \u0 as prefix.

I hope this information proves helpful, and demonstrates that you can encode characters within a regex while still achieving the desired matches. :)

Answer №2

Could you please attempt the following code:

let filter = new Filter({ replaceRegex:  /(\w+)/gi });

Make sure to utilize the replaceRegex option.


This pattern will match everything regardless of case sensitivity.

Here is a breakdown of /(\w+)/gi (with appreciation to regex101):

  1. 1st Capturing Group (\w+).
    1. \w+ matches any word character (equivalent to [a-zA-Z0-9_])
    2. + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
  2. Global pattern flags
    1. i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
    2. g modifier: global. All matches (don't return after first match)

Answer №3

To ensure that your regular expression is Unicode-aware, you should include the u flag. Specifically, modify

/[A-Za-z0-9öÖÇ窺ĞğİıÜü_]/g
to
/[A-Za-z0-9öÖÇ窺ĞğİıÜü_]/gu
(added a u at the end). This will function properly in modern browsers (excluding Internet Explorer), as outlined in this resource. Additionally, there are alternative solutions available for older browser compatibility.

Answer №4

To ensure optimal encoding, convert your JavaScript file to UTF-8 and remember to adjust your meta tag accordingly:

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

Hopefully this adjustment will be beneficial for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to find a partial string match within an array of objects when using Jest?

I am currently utilizing the following versions: Node.js: 9.8.0 Jest: 22.4.2 A function called myFunction is returning an array structured like this: [ ... { id: 00000000, path: "www.someUrl.com/some/path/to" } ... ] I ...

Steps to fill a select dropdown with numbers ranging from 1 to 10, ensuring that each number has a distinct index or value

What is the best way to create a select dropdown containing numbers from 1 to 10, with each option having a distinct value and the default selected option being 1? HTML <select [(ngModel)]="selectNum"> <option value=""> </option& ...

Ways to create different sections for ng-repeat data in AngularJS

I have a list of data elements that I am displaying using ng-repeat which currently prints as follows: data1 data2 data3 data4 data5 data6 However, I would like to display these data elements in sections, like this: data1 data3 data5 data2 data ...

OpenLayers' circular frames surrounding the icons

I am currently using openlayers and trying to implement a feature that creates a circle around the icons on the map. I have been referring to this example on Stack Overflow but unable to draw the circle successfully. Can someone please assist me with this? ...

Having trouble launching a React Native project on an Android simulator?

I encountered a new error while working on my React Native project. I created this project using 'npx react-native@latest init' with the default template: error Failed to install the app. Command failed with exit code 1: gradlew.bat app:installDe ...

What is the best method for having tooltips hover over textboxes?

Hello there, Experts, I am still encountering some difficulties with the tooltips feature. The code snippet below functions properly in displaying the tooltips. However, a major issue arises where it causes the textbox to expand, resulting in misalignmen ...

What is the best way to showcase a collapsible tree using AngularJS and Bootstrap?

I'm currently working on a web application that requires the display of a tree structure using lists. Here is the basic outline: * Node 1 * Node 1.1 * Node 1.1.1 * Node 1.1.1.1 * Node 1.1.2 * Node 1.2 http://jsfid ...

Angular TypeScript Directive Link function not being executed

I've been working on implementing a Role-Based-Access-Control system in my application. The allowed resources are loaded from the server after login, and I was able to verify this using raw JavaScript code. angular.module('app').directive(& ...

Express is unable to locate the specified property

Here is my controller code snippet: exports.showit = function(req, res){ res.render('showpost', { title: req.post.title, post: req.post }) } In my post model, I have included title and name objects: title: {type : String, default : &apos ...

Facing an issue with sending data in AJAX Post request to Django View

I have been trying to send data from the frontend to the backend of my website using AJAX. Below is the post request view in my Django views: def post(self, request): id_ = request.GET.get('teacherID', None) print(id_) args = {} ...

"Encountered a 400 error while trying to add a user in npm

While attempting to execute npm adduser, I provide all the required information but encounter an error: npm http PUT https://registry.npmjs.org/-/user/org.couchdb.user:thecolorred npm http 400 https://registry.npmjs.org/-/user/org.couchdb.user:thecolorred ...

How can one address the issue of undefined data within table cells?

I have encountered an issue while reading and displaying an XML file on a webpage using a JavaScript script. The problem arises when the page loads, and the information inside the cells of the table shows as "UNDEFINED". The intended display should include ...

Can the browser console be used to make a $.get request?

When attempting to initiate an ajax request through the Chrome console, I encountered a strange issue. While console.log() and alert() commands worked as expected, using jQuery's $.get or $.ajax functions only resulted in the entire jQuery function/ob ...

Error: The package [email protected] requires @angular/core@^6.0.3 as a peer dependency, but it is nowhere to be found. This error message is being misleading

Excuse my vague and whimsical question... but could someone please check this for me and confirm if I've lost my mind? Everything appears fine to me. groot@DESKTOP-F9TMEHC MINGW64 /c/mobileDev/Ionic5-go npm ls --depth="0" Ionic5-go C:&b ...

The passport JWT authorization failed, not a single message is being printed to the console

I am currently working on building a login and registration system. I have experience using passport before and had it functioning properly. However, it seems like the npm documentation has been updated since then. I am facing an issue where I cannot even ...

Encountering a Mongoose error during the upsert operation with findOneAndUpdate

While attempting to upsert using findOneAndUpdate, I encountered an error. ValidatedCertificates.findOneAndUpdate( //query { "course": req.body.course_name, "batch": req.body.batch_name }, { //update ...

Does CSS offer a way to specify overflow for selections?

Have you ever noticed that when you highlight text in a textarea, the selection stays within the boundaries of the textarea itself? Take a look: But when you try to select text in other elements, such as a basic div, the selection spills out of the elemen ...

Showing or hiding a div element based on a changing boolean value in Angular

To obtain input from a dynamic form within an ngFor loop, the goal is to display either "correct" or "incorrect" depending on whether the user's answer matches the exercise.question.answer value. The intention is to establish a boolean reactively, bu ...

<select> dropdown menu for selecting specific files opened by JavaScript

Currently, I am converting CSV files into JSON format and then manipulating them to generate arrays that will be used by jQuery to create a graph. My goal is to implement a dropdown menu that allows the user to choose a specific CSV file for graph creatio ...

Displaying only a section of a webpage using AJAX

Currently, I am utilizing an ajax call to showcase a PHP page, which is functioning correctly as shown below: <script type="text/javascript"> var xhr = false; if (window.ActiveXObject){ xhr = new ActiveXObject("Microsoft.XMLHTTP"); ...