Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struggling with regex to match only two of a character, not three

I need to match all occurrences of // in a string in a Javascript regex

It can't match /// or /

So far I have (.*[^\/])\/{2}([^\/].*)

which is basically "something that isn't /, followed by // followed by something that isn't /"

The approach seems to work apart from when the string I want to match starts with //

This doesn't work:

//example

This does

stuff // example

How do I solve this problem?

Edit: A bit more context - I am trying to replace // with !, so I am then using:

result = result.replace(myRegex, "$1 ! $2");
like image 944
Fiona - myaccessible.website Avatar asked Oct 29 '25 15:10

Fiona - myaccessible.website


1 Answers

Replace two slashes that either begin the string or do not follow a slash, and are followed by anything not a slash or the end of the string.

s=s.replace(/(^|[^/])\/{2}([^/]|$)/g,'$1!$2');
like image 78
kennebec Avatar answered Oct 31 '25 03:10

kennebec