简体   繁体   English

RegExp for Javascript获取子字符串

[英]RegExp for Javascript to get a substring

I would like to parse some plain text that I got from the Twitter API. 我想解析从Twitter API获得的一些纯文本。 What I need to do is basically search through a tweet to find a "@" character followed by some text and replace the plain text with an anchor linked to that text. 我需要做的基本上是搜索一条推文,以找到一个“ @”字符,后跟一些文本,然后用链接到该文本的锚点替换纯文本。 For example: 例如:

Take the tweet plain text: "@flintzke this is a test" 使用推文纯文本:“ @ flintzke,这是一个测试”

and use a Regular expression to turn it into: 并使用正则表达式将其转换为:

<a href='www.twitter.com/flintzke'>@flintzke</a> this is a test

my guess was to use this kind of function: 我的猜测是要使用这种功能:

function getUsernameLink(text) {
var exp = /^[@][a-zA-Z0-9_!@#%&*]*[\s]$/ig;
return text.replace(exp, "<a href='https://twitter.com/$1'>$1</a>");
}

my objective was to find an expression that found a single word in a string, text, that starts with "@" and ends with a whitespace 我的目标是找到一个表达式,该表达式在字符串,文本中找到一个单词,该单词以“ @”开头,以空格结尾

I think you have tried a bit to hard ;). 我认为您已经尝试了一些;)。 Firstly the anchors ^ and $ mark the beginning and end of the string (not the beginning and end of the match or something - which I suppose you assumed). 首先,锚^$标记字符串的开头和结尾(而不是匹配的开头和结尾或其他东西-我想您是假设的)。 Then you use $1 but that corresponds to the first capture (the first set of parentheses - which you don't have). 然后,您使用$1但是它对应于第一个捕获(第一组括号-您没有)。 Either add parentheses around your match or use $& . 在您的匹配项周围添加括号,或使用$& And lastly, \\S represents a non-whitespace character. 最后, \\S表示非空白字符。 So why not just match as many non-whitespace characters as possible? 那么,为什么不匹配尽可能多的非空白字符呢?

exp = /@(\S*)/g;
return text.replace(exp, "<a href='https://twitter.com/$1'>@$1</a>");

试试这个:

text.replace(/\@(\w+)/g,"<a href='https://twitter.com/$1'>@$1</a>");

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

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