I want to remove a specific word from a string using Regex and JavaScript. I have strings like below
Zoe-Clean-1-1024x678
Zoe-Clean-1-150x150
Zoe-Clean-1-1536x1017
Zoe-Clean-1-1700x1126
Zoe-Clean-1-2048x1356
Zoe-Clean-1-300x199
Zoe-Clean-1-768x509
Zoe-Clean-1-900x596
Zoe-Clean-1-scaled
Zoe-Clean-1
zoko-150x150
zoko-300x300
Zoo-Studio-Logo-for-Pay-150x150
Zoo-Studio-Logo-for-Pay-300x300
Zoo-Studio-Logo-for-Pay-768x768
Zoo-Studio-Logo-for-Pay
I want to remove the Logo, for, Pay, scaled word, resolution size 150x150, 300x300, etc., and remove the dash character -. So I expect I can only get the main name.
Zoe-Clean-1 -> Zoe Clean
Zoe-Clean-1-scaled -> Zoe Clean
Zoe-Clean-1-300x199 -> Zoe Clean
Zoo-Studio-Logo-for-Pay -> Zoo Studio
Zoo-Studio-Logo-for-Pay-768x768 -> Zoo Studio
Currently, I'm using this code name.replace(/\b(Logo|for|Pay)\b/gm, ""), I don't know how to remove the dash and resolution size.
CodePudding user response:
name = name.replace(/(Logo|for|Pay|[0-9] x[0-9] |-[0-9] [-|$|\s])/gm, "") ;
name = name.replace(/-/gm, " ") ;
name = name.trim() ;
First, remove all we don't want : [0-9] x[0-9] match the resolution size, -[0-9] [-|$|\s] match number with à dash before and a dash after or à line break/line end.
Then you replace all the - by space : name.replace(/-/gm, " ").
So you just have to trim() the string !
CodePudding user response:
You can use
name = name.replace(/-Logo-for-Pay|-\d.*/g, '')
See the regex demo
Details:
-Logo-for-Pay- a fixed substring|- or-\d.*- a hyphen, a digit and then the rest of the line.
