Home > other >  Removing wording in front and back of a string via regex or use replace instead?
Removing wording in front and back of a string via regex or use replace instead?

Time:11-04

I want to remove wording from the front and end of a string (taken from page title of Google Slide in presenter view)

Presenter view - Custom title may contain numbers or special characters - Google Slides

Since the middle part may contain anything unexpected, would using replace() be better than regex?

I want to remove: "Presenter view - " and " - Google Slides", which I expect always to be the same. The below works for me:

const slidetitle = document.title.replace("Presenter view - ", "").replace("- Google Slides", "");

With regex I tried below but not working:

const slidetitle = document.title.match(/(?<=Presenter view - ).*(?<= - Google Slides)$/)[1];

CodePudding user response:

Something like this could work:

/^[^-] - | -[^-] $/gm
  • ^[^-] - - capture everything not a dash from the beginning of the line leading up to dash space
  • | - or
  • -[^-] $ - find the last space dash and capture everything not a dash till the end of the line
  • gm - global multiline modifiers

console.log(`Presenter view - Custom title may contain numbers or special characters - Google Slides`.replace(/^[^-] - | -[^-] $/gm, ''));


Using the solution above affords you the chance that "Presenter view - " and " - Google Slides" are not guaranteed. If they are guaranteed then:

/^Presenter view - | - Google Slides$/gm
  • Related