String: 56abc67xyz, 56abc67xyz68xyz, 12abc69xyzA
Output: 56abcxyz, 56abc67xyzxyz, 12abc69xyzA
So, the numbers occurring right before xyz should be removed but there shouldn't be anything after the xyz. It should be the last thing in the string.
CODE:
mystring.replace(/\d xyz$/, '')
This code will remove the last xyz but I want to keep it as in example above.
CodePudding user response:
Use a Positive Lookahead: (?=)
. So if you want to check if something is there, but not match it, put it after the =
, like this: \d (?=xyz$)
console.log('56abc67xyz'.replace(/\d (?=xyz$)/, ''))
console.log('56abc67xyz68xyz'.replace(/\d (?=xyz$)/, ''))
console.log('12abc69xyzA'.replace(/\d (?=xyz$)/, ''))