Reputation: 9
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'
Upvotes: 0
Views: 1556
Reputation: 160
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
)
Upvotes: 0
Reputation: 138235
string.replace(/\@[^\s]*/g, "")
Use a regex to match every @ followed by non whitespace characters. Replace those with an empty string.
Upvotes: 4