Yerlan Yeszhanov
Yerlan Yeszhanov

Reputation: 2439

And operator in regex?

I have a string with special marks in string and I want to delete them.

here is my string:

let message='Hello my name is /# Jane #/, if from /# company#/'. Could you please call me back .

now I'm trying to delete this /#---#/ marks

message.replace(/#/g, "")

but how add "AND" operator in regex to delete '/' too.

Upvotes: 1

Views: 97

Answers (2)

marsze
marsze

Reputation: 17055

Or, more specific (replace /# or #/):

message.replace(/\/#|#\//g, "")

(You have to escape the / with \/)

Another more complex approach, which might or might not work depending on your use cases:

let message = 'Hello my name is /# Jane #/, if from /# company#/. Could you please call me back.';
// replace in pairs and take care of extra whitespace
let regex = /\/#\s*(\w+)\s*#\//g;
message = message.replace(regex, "$1");
console.log(message);

Upvotes: 3

Toto
Toto

Reputation: 91430

Use a character class:

message.replace(/[#\/]/g, "")

let message='Hello my name is /# Jane #/, if from /# company#/. Could you please call me back .';
console.log(message.replace(/[#\/]/g, ""));

If you want to remove character # and / only when they are close together, use the following, it also replaces extra spaces

let message='Hello my name is /# Jane #/, if from /# company#/. Could you please call me back .';
console.log(message.replace(/\/#\s*|\s*#\//g, ""));

Upvotes: -1

Related Questions