简体   繁体   English

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

[英]Remove word from string beginning with a certain character

let string = 'the username @bradley is ready'

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

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

Use a regex to match every @ followed by non whitespace characters .使用正则表达式匹配每个 @ 后跟非空白字符 Replace those with an empty string.用空字符串替换它们。

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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM