0

So basically given this string iiisdoso i want to extract all the part of the string before but excluding the letter o. So basically iiisd and s. I current just have

const data = "iiisdoso"
const regex = /(.*?)o/g

console.log(data.match(regex))

but this result includes the o in but my goal is return results up to but excluding o

Udendu Abasili
  • 1,163
  • 2
  • 13
  • 29
  • 2
    Look up `[]` in regex. It is called [character classes](https://www.rexegg.com/regex-quickstart.html#classes) – vrintle Apr 16 '20 at 05:49
  • Does this answer your question? [Negate characters in Regular Expression](https://stackoverflow.com/questions/1763071/negate-characters-in-regular-expression) – vrintle Apr 16 '20 at 05:51
  • in this case i would suggest doing a split on "o" or whatever other condition you may have – Phu Ngo Apr 16 '20 at 06:39

1 Answers1

1

As already mentioned in the comments you can achieve this with negations and character classes:

const data = "iiisdoso"
const regex = /([^o]+)/g

console.log(data.match(regex))

This will give you the desired result

["iiisd", "s"]

But this does match any string with no "o" after it too! To avoid this, you need to use

const regex = /([^o]+)o/g

In this case the "o" is included in the matches and must be deleted for each string the result-array - e.g. with

mymatch.replace('o','')

Interesting: If you use

const regex = /([^o]*)/g

The result is

["iiisd", "", "s", "", ""]

This is something I don't understand. Well - I understand that an empty string matches the regex too and can be placed right before the "o". But why do we get a third empty string at the very end?

Arno
  • 447
  • 4
  • 12
  • 1
    the third empty string at the very end matches the empty string after the "o" at the end of the whole string – Phu Ngo Apr 16 '20 at 06:38
  • Good point - you are right. This gave me the idea that my first solution will match any string without subsequent "o" too. I edited my answer and added this point. – Arno Apr 16 '20 at 08:44