javascript - 查找并替换特定字符串

标签 javascript regex replace

我有一个字符串(一条推文),如下所示:

var str = "blah blah blah blah http://example.com blah blah #something blah blah https://example.com blah blah @person"

我想挑选出所有应该是链接的内容并用链接标签将其包裹起来。需要在字符串中找到以下 4 个内容:

  • 任何以@开头的单词
  • 任何以#开头的单词
  • 任何以http://开头的单词
  • 任何以 https:// 开头的单词

所以我想它会有点像这样:

str.replace(regexForHashtag, '<a href="' + linkText + '">" + linkText + "</a>");

最佳答案

基于Parsing Twitter Usernames, Hashtags and URLs with JavaScript :

String.prototype.parseURL = function() {
    return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
        return url.link(url);
    });
};

String.prototype.parseUsername = function() {
    return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
        var username = u.replace("@","");
        return u.link("http://twitter.com/"+username);
    });
};

String.prototype.parseHashtag = function() {
    return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
        var tag = t.replace("#","%23");
        return t.link("http://search.twitter.com/search?q="+tag);
    });
};

String.prototype.parseTweet = function() {
  return this.parseURL().parseUsername().parseHashtag();
};

可以这样调用:

var str = "blah blah blah blah http://example.com blah blah #something blah blah https://example.com blah blah @person"

str.parseTweet();
// or:
// str.parseURL
// str.parseUsername
// str.parseHashtag

参见this jsBin

关于javascript - 查找并替换特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29286763/

相关文章:

javascript - 在服务层将数据推送到Ember存储并返回promise

javascript - 如何在 NodeJS Selenium 中使用代理?

javascript - 这个正则表达式(VBScript/JavaScript 风格)有什么问题?

javascript - 使用正则表达式替换引导列类

JQuery 从输入文本中查找并替换文本区域中的字符

javascript - 为什么这个 <div> 元素不会按照我希望的方式移动到使用 jQuery 的方式?

javascript - 如何将输入中的值插入到数组中?

python - 正则表达式中的 anchor

java - 文本中的子字符串替换

javascript - 替换多个包含 $ 符号的字符串