I need a regex for javascript that allows me to select a single character with a restriction: that it does NOT have a specified character besides itself.
I need to select the character /
but only if it does NOT have the character a
besides it.
E.g.:
str = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t";
myregex = ????
var patt = new RegExp(myregex);
var res = patt.split(str);
And the result should be something like this:
res[0] = "I Like this"
res[1] = " and a/ basketball is round a/a ups.Papa/ tol"
res[2] = "d "
res[3] = "me tha/t"
The regex should be something like:
(if a then not)(\/)(if a then not)
I have no idea how to do it, I tried: [^a](\/)[^a]
, but then it selects also the characters that are beside the /
, like s/
, l/d
, not the a
's; I don't want to select the characters beside the /
.
Split by /(?<!a)\//g
var output = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t".split(/(?<!a)\//g);
console.log(output);
Explanation
/(?<!a)\/
matches /
which is not preceded by a
Note
Edit
Or alternatively, you can just split by /
var output = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t".split(/\//g);
output = output.reduce( function(a,c){
var lastItem = a.slice(-1)[0];
//console.log(lastItem)
if ( lastItem && lastItem.slice(-1) == "a" )
{
a.pop();
a.push(lastItem.concat("/").concat(c));
}
else
{
a.push(c);
}
return a;
}, [])
console.log(output);
Edit 2
If a
has to be ignored on either sides of /
, then use the previous answer (based on reduce), just add the look-ahead in split
var output = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t".split(/\/(?!=a)/g);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With