Salim Shamim
Salim Shamim

Reputation: 686

Remove forward slash but not date format in a string REGEX

I have string of the following format

Pending status started at 11/03/2019 11:32
User: XY_Z
moj/f112
Reason: Linked to Major/P1 Ticket

In the above scenario I want to remove the forward slash (/) in moj/f112 and Major/P1 but not in the date i.e 11/03/2019.

I tried \D\/\D/ig but then it will select all the forward slashes and did some trials like ^(\d{2}\/\d{2}\/\d{4})(and ?)\D\/\D/ig . I am not used to working with regular expressions, and running short of time.

Any help ?

Thanks a lot in advance. :)

Upvotes: 0

Views: 893

Answers (3)

Pal Singh
Pal Singh

Reputation: 1974

This regex will match {slash + two digits + slash} and rest of the slashes and then we can replace rest of the slashes.

const str = `Pending status started at 11/03/2019 11:32
User: XY_Z
moj/f112
Reason: Linked to Major/P1 Ticket`;

const regex = /(\/\d{2}\/)|\//g;
let modifiedStr = str.replace(regex, '$1');
console.log(modifiedStr)

Working example

Upvotes: 1

Md. Iman Ali
Md. Iman Ali

Reputation: 34

Here is another option.

var str = `Pending status started at 11/03/2019 11:32
User: XY_Z
moj/f112
Reason: Linked to Major/P1 Ticket`;

var newString = str.replace(/[^\d{1,2}\/\d{1,2}\/\d{4}]\//gm, '');

console.log(newString);

Upvotes: 0

anubhava
anubhava

Reputation: 785176

You may use this alternation regex to first match and group what you want to keep and then match / as last option in alternation:

var str = `Pending status started at 11/03/2019 11:32
User: XY_Z
moj/f112
Reason: Linked to Major/P1 Ticket`

var re = /(\b(?:\d{1,2}\/){2}\d{4}\b)|\//

var repl = str.replace(re, '$1')

console.log(repl)

RegEx Demo

Upvotes: 1

Related Questions