1

How would I remove specific, yet slightly random text from a string in JavaScript?

EG:

a string var string = "!warn <@123456789123456789> I eat apples for breakfast"; The !warn will always be at the start. <@ will always be at the start of the numbers. > will always be at the end of the numbers. The <@****> numbers are random and are never the same. The length of the <@****> can range between 18-20 numbers.

I want to end up with the string I eat apples for breakfast.

Thanks!

1
  • 1
    Have you tried anything? I'd suggest using RegEx. Commented Apr 2, 2018 at 23:06

2 Answers 2

3

An alternative is using regex

Explanation: https://regex101.com/r/SLhRMA/1

var str = "!warn <@123456789123456789> I eat apples for breakfast";

console.log(str.replace(/!warn <@\d+>\s?/, ''))

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

4 Comments

My thought is console.log(str.replace(/(?:\!warn \<@\d+\>)(.*?)/, '$1'))
@Sphinx your approach is beautiful!
@Sphinx You'd probably want to trim that once making the replacement. Good approach though.
@SimonR, Yes, but that is not a big problem. I am thinking if the string is very large, which method will be more efficiency.
1

var text = "!warn <@123456789123456789> I eat apples for breakfast";

console.log(text.replace(/^\!warn <@.*?>\s?/,""));

How this works is it replaces the text based on the pattern provided (/\!warn <@.*?>\s?/s).

The first part is a literal check that it says !warn at the very beginning of the string (we escape the explanation point because that has a pattern meaning). Then we're checking for <@ and then any characters between the @ and >. We're using a non-greedy check - so it'll match up to the first >. Then we're checking for one single space so it makes the very first part of the bit you want as the first character.

An explaination of this is available on Regex101

Comments

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.