Home > Blockchain >  replace all the special characters except numbers with javascript / node js
replace all the special characters except numbers with javascript / node js

Time:03-27

I am trying to replace all the special characters even space but not numbers with - but if there are multiple special characters like [/// then it should only replace -

I have added my expected output in snippet

const string= "![astronaut-lost-in-space-rk](//images.ctfassets.net/c8qz6f7npv42/fJd9r4N1eriItv5XNp0uv/4b46d52459ea20684c653a1c200b5aa1/astronaut-lost-in-space-rk.jpg)";

console.log(string.replace(/[^a-zA-Z ]/g, "-"));

console.log("Expected Output")

console.log("-astronaut-lost-in-space-rk-images-ctfassets-net-c8qz6f7npv42-fjd9r4n1eriitv5xnp0uv-4b46d52459ea20684c653a1c200b5aa1-astronaut-lost-in-space-rk-jpg-")

In snippet you can see I have 4 special characters present at like this ])\\ and it getting replace by - by 4 times ---- I want to replace special characters but if it present more then 1 then it should replace every special character but show only one -

CodePudding user response:

You have to use plus-sign( ) plus toLowerCase() to get expected output

const string= "![astronaut-lost-in-space-rk](//images.ctfassets.net/c8qz6f7npv42/fJd9r4N1eriItv5XNp0uv/4b46d52459ea20684c653a1c200b5aa1/astronaut-lost-in-space-rk.jpg)";

console.log(string.replace(/[^a-zA-Z0-9] /g, '-').toLowerCase());

console.log("Expected Output")

console.log("-astronaut-lost-in-space-rk-images-ctfassets-net-c8qz6f7npv42-fjd9r4n1eriitv5xnp0uv-4b46d52459ea20684c653a1c200b5aa1-astronaut-lost-in-space-rk-jpg-")

I hope this is your expected output

CodePudding user response:

You can use the plus-sign ( ) to match 1 or more characters in a row:

string.replace(/[^a-zA-Z0-9] /g, '-')

This will give you the expected output

CodePudding user response:

You can use both \w to represent the characters you want to keep and the to match one or more consecutive ones and then replace that block with a "-".

const str = "![astronaut-lost-in-space-rk](//images.ctfassets.net/c8qz6f7npv42/fJd9r4N1eriItv5XNp0uv/4b46d52459ea20684c653a1c200b5aa1/astronaut-lost-in-space-rk.jpg)";

let result = str.replace(/[^\w] /g, "-");

console.log(result);

The \w is a shortcut that is equivalent to [A-Za-z0-9_]. If you don't want the underscore included, then you can skip the shortcut:

const str = "![astronaut-lost-in-space-rk](//images.ctfassets.net/c8qz6f7npv42/fJd9r4N1eriItv5XNp0uv/4b46d52459ea20684c653a1c200b5aa1/astronaut-lost-in-space-rk.jpg)";

let result = str.replace(/[^A-Za-z0-9] /g, "-");

console.log(result);

  • Related