0

This might be pretty simple, but I am having a hard time with it. Consider the following code:

var string = 'testingT#$^%#$ESTING__--232'
string = string.match(/^\w*$/)
if (string != null)
{
    string = string.join('')
    string = string.toUpperCase()
}
$('#my-input').val(string)

What I want to do, is to strip all characters that aren't alphanumeric or underscore from string, and then transform that string to uppercase.

So far I did that, it works perfectly if I don't add any special characters, but when I add - or ^ to it, for example, it deletes everything from #my-input

3 Answers 3

3

You can do this in one step:

string = string.replace(/[^\w]/g, '').toUpperCase();
console.log(string); //=> "TESTINGTESTING__232"
Sign up to request clarification or add additional context in comments.

Comments

1
var string = string.replace(/[^a-zA-Z_0-9]/g,'').toUpperCase()

Also, do you need unicode? My regex will only match a-z, and not åÉø for example.

Comments

1

You need use 'global' flag in regex and remove match restriction.

var str = 'testingT#$^%#$ESTING__--232';
str = str.match(/\w+/g);    
if (str !== null)
{
    str = str.join('');
    str = str.toUpperCase();
}
$('#my-input').val(str);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.