XRegExp to JavaScript RegExp

424 views Asked by At

I want to convert a XRegExp function to pure JavaScript RegExp. Basically all non-alphanumeric character will be replaced with "_" including spaces.

The text

This is a sample text *\&^%$#@!~'

will be like

This_is_a_sample_text____________

I have the following code.

var text = "This is a sample text *\&^%$#@!~'";
var matchAlphaNumeric = new XRegExp('[\\p{L}\\p{N}]');
var result = substituteNotAcceptedCharactersforTag(text, matchAlphaNumeric);
function substituteNotAcceptedCharactersforTag(text, regex) {
        var tagWithAlphaAndNumeric = '';
        for (var i = 0; i < text.length; i++) {
            var characterBeingTested = text.charAt(i);
            if (XRegExp.test(characterBeingTested, regex) === true) {
                tagWithAlphaAndNumeric += characterBeingTested.toLowerCase();
            } else {
                tagWithAlphaAndNumeric += '_';
            }
        }
        return tagWithAlphaAndNumeric;
    }
1

There are 1 answers

1
Robby Cornelissen On BEST ANSWER

Replace all non-alphanumeric characters with _:

s = s.replace(/[^0-9A-Za-z]/g, '_');