How to remove part of a string to a certain point

Asked

Viewed 40 times

-1

Good morning everyone. I’m starting with Javascript and I’m having a hard time removing a part of a string up to a certain point.

got the string:

"21/07/2020 16:34:42 - Adriana gomes carneiro (Comments) daniel test" OR "21/07/2020 16:34:42 - Daniel silva (Comments) COMMENT REJECTED" The name after the date will always change.

I would like to remove part of the string until "(Comments)...", keeping for example: "(Comments) COMMENT REJECTED".

Can someone help me?

  • Before anything, start by doing the tour to understand how the community works; then read the How to ask to check how you can improve your question. Post what you have found so far, post your full code so that it can be helped and will help others in the future.

1 answer

0


One way to solve it is to use the index together with the method substring, to extract the necessary strings. Follow an example:

const linha = "21/07/2020 16:34:42 - Adriana Gomes Carneiro (Comments) TESTE DANIEL";
const idx = linha.indexOf(" (Comments) ");
const primeiraParteStr = linha.substring(0,idx);
// "21/07/2020 16:34:42 - Adriana Gomes Carneiro"
const segundaParteStr = linha.substring(idx, linha.length);
// " (Comments) TESTE DANIEL"

Note that in the variable segundaParteStr, we have a space at the beginning of the string (maybe unwanted), to remove just use the method Trim().

segundaParteStr = linha.substring(44,linha.length).trim()
  • Thank you. You helped a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.