从字符串中删除以某个字符开头的单词

时间:2019-12-11 16:02:39

标签: javascript

let string = 'the username @bradley is ready'

如何去除以@符号开头的所有单词,以便输出为“用户名已准备好”

2 个答案:

答案 0 :(得分:4)

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

使用正则表达式匹配每个@,后跟non whitespace characters。将其替换为空字符串。

答案 1 :(得分:0)

这是一个解决方案,应从您的字符串中删除以@开头的单词。 它应该保留标点符号,而不要创建重复的空格。 (尽管此解决方案不排除电子邮件)

// \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
)