0

let string = 'the username @bradley is ready'

How can I strip all words which begin with the @ symbol so that the output is 'the username is ready'

  • I would use regex replace: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – Dean Dec 11 '19 at 16:04

2 Answers2

4
 string.replace(/\@[^\s]*/g, "")

Use a regex to match every @ followed by non whitespace characters. Replace those with an empty string.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

Here's a solution that should remove words starting with @ from your strings. It should preserve punctuation and not create duplicate spaces. (This solution does not exclude emails though)

// \s? optional preceding space
// [^\s.,!?:;()"']+ at least one character that isn't a space or punctuation
// ([.,!?:;()"'])? an optional punctuation character, saved to a capture group
    
function stripUserHandles (string) {
  return string.replace(/\s?@[^\s.,!?:;()"']+([.,!?:;()"'])?/g, "$1")
}
    
console.log(
  stripUserHandles('The username @bradley is ready')
  // The username is ready
)
console.log(
  stripUserHandles('The username is @bradley. It is ready')
  // The username is. It is ready
)
console.log(
  stripUserHandles('Alright "@bradley", Here\'s your username')
  // Alright "", Here's your username
)
Alexander Rice
  • 160
  • 1
  • 5
  • I see in an earlier comment that you only want to match words with a space before and after. If this is the case, all you should need is `.replace(/\s@\S+\s/g, ' ')` we match a space on each side and allow one or more non-space characters following an @. We then replace the whole match with a single space. – Alexander Rice Dec 11 '19 at 17:08