繁体   English   中英

javascript根据字符获取子字符串

[英]javascript get substring based on character

我有一个RSS feed,其提供的值为

author@email.com(作者)

我知道我可以用

author = author.split('(')[1];

但这仍然留下

作者)

我知道我可以再拆分

author = author.split(')')[0];

但是,有一种方法可以做到这一点吗?

这是我的代码

            var title = $(this).find('title').text();
            var author = $(this).find('author').text();
            author = author.split('(')[1];
            author = author.split(')')[0];
            var description = $(this).find('description').text();
            var guid = $(this).find('guid').text();

您可以使用正则表达式来做到这一点。

 var author = "author@email.com (Author)"; var result = author.replace(/.*\\(|\\)/g,"") console.log(result); 

这确实只是替换了之前(和最后一个)

由于您只想摆脱字符串中的最后一个字符,因此可以使用slice方法。 第一个参数是开始位置(从零开始计数),第二个参数是结束位置。 您可以使用负索引从背面开始计数(例如-1是最后一个字符,-2是倒数第二个字符)。

使用此代码,您可以编写:

author = author.split('(')[1].slice(0, -1);

我将使用带有捕获组的正则表达式:

var authorRegex = /^(.*)\s+\((.*)\)$/;
var authorInfo = authorRegex.exec(author);
var email = authorInfo[1];
var name = authorInfo[2];

您可以在一行中将已经完成此功能的功能链接在一起。

var author = $(this).find('author').text().split('(')[1].split(')')[0]

而不是使用split,在这种情况下,您可以尝试使用replace的正则表达式,例如:

author = author.replace(/^.+\(([^\(\)]+)\)[\s\t]*$/, '$1');

它将文本保存在字符串末尾的()中,并将其替换为整个字符串。

暂无
暂无

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

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