2

I have a below string. I need to remove all the special character and space.

var Uid = "s/Information Needed1-s84102-p306";

I tried the below code.It didn't replace the space from the string.

console.log(Uid.replace(/[^\w\s]/gi, '')}")

The output is:- sInformation Needed1s84102p306

I want the output as sInformationNeeded1s84102p306

1
  • Please clarify if _ should be removed or not. Commented Sep 11, 2015 at 10:33

3 Answers 3

6

Simply try using

/[\W_]/g
  • \W match any non-word character [^a-zA-Z0-9_]

Included _ if you also want to remove it then

Regex

Sign up to request clarification or add additional context in comments.

Comments

3

You can just use:

console.log(Uid.replace(/\W+/g, '')}")

\W will match any non-word character including a space.

RegEx Demo

2 Comments

you don't actually need the +, right? since you have the g.
Even if g flag + is good for efficiency purpose as more than one non-word characters get replaced in one go.
2

You can use this expression for your case

var x = "s/Information Needed1-s84102-p306";
console(x.replace(/[^A-Z0-9]/ig, ""));

Here is the working Link

1 Comment

Interesting, this solution might turn out better if _ should be removed too.

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.