0

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.

1 Answer 1

3

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$)/, ''))

Sign up to request clarification or add additional context in comments.

8 Comments

I would use \b instead of $ to capture a word boundary.
@richard good job upvoted, but I want to suggest also some little fixes if I can. 1) in the second use /g and not $. and it will be something like this /\d+(?=xyz)/g . g means global so it will check for multiple times (from left to right)
@LaaouatniAnas Why do we need to check multiple times from left to right? There is only one occurrence and it occurs at the end of the string. Please let me know if I'm missing something.
@ITgoldman what is the advantage of using \b over $ in this case?
just to match a few repetition of strings inside bigger text
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.