0

I wanted to do some regex search on strings and remove that part of the string that matches.

Eg. I have following strings

xyz-v1.0.0#
abc-v2.0.0#
def-v1.1.0#

So, for such cases, I wanted to remove -v1.0.0#, -v2.0.0# and -v1.1.0# from these strings.

So, for this what regex can I use and how can I remove them in Node JS?

1
  • Can you put the code you tried so far? Commented Nov 1, 2017 at 22:15

1 Answer 1

1

You can do this

.replace(/-.*$/, '') will check for -{anything} at the end of the string and replace with nothing.

const strs = [
  'xyz-v1.0.0#',
  'abc-v2.0.0#',
  'def-v1.1.0#'
];
const newStrs = strs.map(str => str.replace(/-.*$/, ''));
console.log(newStrs);

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

7 Comments

You could also use the regular expression /-v.*$/ to make sure that it is replacing the version at the end of the string.
there is actually one issue here. say, if string is abc-vxy-v1.0.0#, then it is removing -vxy-v1.0.0#, I only want to remove from last dash(-)
Okay, you can use this regular expression /-v\d+\.\d+\.\d+#$/ to match this specific format -v{number}.{number}.{number}#. I have to go out now, but i'll think of something better later.
Yeah this is one way. This is also not always correct, I am thinking if somehow I could detect last dash(-) somehow, that would be best. like instead of .*, restriction on dot(.) to not include dash(-)
Try adding $ at end of the regular expression, it should only match the end of the string
|

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.