0

I want to remove all special characters from string and add only one "-"(hyphen) in the place.

Consider below example

var string = 'Lorem%^$&*&^Ipsum#^is@!^&simply!dummy text.'

So, from the above string, if there is a continuous number of special characters then I want to remove all of them and add only one "-" or if there is a single or double special character then also that should be replaced by "-"

Result should be like this

Lorem-Ipsum-is-simply-dummy text-

I have tried below, but no luck

var newString = sourceString.replace(/[\. ,:-]+/g, "-");
14
  • added tried code Commented May 9, 2018 at 6:04
  • . also should get removed, and _ as well Commented May 9, 2018 at 6:06
  • so sorry for that, i have changed the question. Commented May 9, 2018 at 6:09
  • do you want leading/trailing - kept or removed? Commented May 9, 2018 at 6:12
  • why u downvote to this question? Commented May 9, 2018 at 6:19

1 Answer 1

4

You could use .replace to replace all non-alphabetical character substrings with -:

const input = 'Lorem%^$&*&^Ipsum#^is@!^&simply!dummy text.';
const output = input.replace(/[^\w\s]+/gi, '-');
console.log(output);

If you want to permit numbers too:

const input = 'Lorem123%^$&*&^654Ipsum#^is@!^&simply!dummy text.';
const output = input.replace(/[^\w\s\d]+/gi, '-');
console.log(output);

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

8 Comments

/[^a-z0-9]+/gi ?
could you help me to remove the . as well. i will be thankfull
what do you mean? it does do that!
@AmolRokade It's already removed from the string..? I want to remove all special characters from string and add only one "-" in the place.
@AmolRokade Your desired output includes the space. I highly recommend trying to figure out what you want the output to be like before posting a question.
|

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.