2012-04-25 57 views
1

我有一个论坛,我想自动解析一些主要的链接。例如,如果用户发布这样的帖子:在关键字前添加字符串 - javascript

您应该访问StackOverflow。我在维基百科找到它。

它会自动解析这样的:

您应该访问< A HREF = “http://stackoverflow.com” >的StackOverflow < /一>。我发现它在< a href =“http://en.wikipedia.org/wiki/”>维基百科</a >。

这仅仅使用JavaScript是可行的吗?

感谢您的协助。 :-)

+0

你预先处理文本你把之前在DOM,或添加这些链接,一旦文本alreadyh在DOM? – 2012-04-25 16:51:27

+0

这不是简单地用其他词替换单词吗? http://www.w3schools.com/jsref/jsref_replace.asp – DanRedux 2012-04-25 16:51:29

+0

有一个很像你的已经在StackOverflow上semilar问题:http://stackoverflow.com/questions/119441/highlight-a-word-with-jquery – YMMD 2012-04-25 16:52:01

回答

1

如果你预先处理的文本,可以使用交替使用replace功能与callback和正则表达式:

var str = "You should visit StackOverflow. I found it on Wikipedia."; 
str = str.replace(/StackOverflow|Wikipedia|etc/gi, function(m) { 
    var href; 
    switch (m.toLowerCase()) { 
     case "stackoverflow"; 
      href = "http://stackoverflow.com"; 
      break; 
     case "wikipedia"; 
      href = "http://en.wikipedia.org"; 
      break; 
     // ...and so on... 
    } 
    return '<a href="' + href + '">' + m + '</a>'; 
}); 

YMMD指出,上述要求定义每个关键字两次,这是事实。当我已经与大量的关键字要做到这一点,我已经具有与该关键字作为按键,href值值的对象来完成它,并建立动态的表达:

// ==== Setup code you presumably do once 

// The substitutions -- make sure the keys are in lower case 
var substitutions = { 
    "stackoverflow": "http://stackoverflow.com", 
    "wikipedia":  "http://en.wikipedia.org", 
    // ...and so on... 
}; 

// Build the regex. Here I've used `Object.keys` which is an ES5 feature 
// but you can use an ES5 shim (since it's something a shim can provide). 
// Note that if your keywords include any special regular expression 
// characters, you'll have to loop through the keys manually and escape 
// those. 
var subrex = new RegExp(Object.keys(substitutions).join("|"), "gi"); 

// ==== Where you're using it 
var str = "You should visit StackOverflow. I found it on Wikipedia."; 
str = str.replace(subrex, function(m) { 
    return '<a href="' + substitutions[m.toLowerCase()] + '">' + m + '</a>'; 
}); 

Live example | source

+0

这是恕我直言,并不理想,因为你必须定义关键字两次。实现这一点绝对有更好的办法。 – YMMD 2012-04-25 16:56:21

+0

@YMMD:你没有*,你可以做我以前做过的事情,并开始使用散列并动态构建正则表达式。我会添加一个例子。 *编辑*完成 – 2012-04-25 16:57:58

+0

对我来说,这似乎是一个更好的。 :-)感谢您更新您的答案! – YMMD 2012-04-25 17:05:18

1

是的,使用String.replace(regex,replaceString)来做到这一点。

下面是一个例子:

var text = "You should visit StackOverflow. I found it on Wikipedia."; 

var newText=text.replace(/stackoverflow/gi, 
         "<a href='http://www.stackoverflow.com/'>StackOverflow</a>"); 

g代表全球性的,所以它将替换所有实例和i指不区分大小写的搜索。

如果您要更换的常用词,如“字典”链接到dictionary.com它会更好,如果你只是换掉它,如果你的用户增加了一个特殊的标记,例如:

"You should visit StackOverflow. I found it on Wikipedia." 

不应该可以用链接替代,除非它是这样写的:

"You should visit &StackOverflow. I found it on Wikipedia." 

那么你的方法将只需要添加特殊符号。

另外,我想拥有的数据在一个这样的数组:

var linkArray = [ ["StackOverflow", "http://www.stackoverflow.com/", "Description"], 
        ["Wikipedia", "http://wikipedia.org/", "Free encyclopedia"] ]; 

然后创建一个循环来查找和替换的实例:

function addLinks(textInput) { 
    for (var i=0; i<linkArray.length; i++) { 
     textInput = addLink(textInput, linkArray[i]); 
    } 
    return textInput; 
} 

function addLink(textInput, link) { 
    var replaceString = "<a href=\"" + link[1] + "\" title=\"" 
         + link[2] + "\">" 
         + link[0] + "</a>"; 
    return textInput.replace(new RegExp("&"+link[0], "gi"), replaceString); 
} 
1

你想创造一个干净什么,可扩展的代码是创建一个word =>链接的库,然后你可以遍历它并在代码中进行替换。

这里是一个小提琴演示做的,如果目标 字符串包含不同的情况下替换字符串的变体http://jsfiddle.net/MjV84/

$(function() { 

    var text = $('#foo').text(), 
     library = { 
      stackoverflow: 'http://stackoverflow.com', 
      wikipedia: 'http://wikipedia.com' 
     }, 
     name; 

    for (name in library) { 
     text = text.replace(new RegExp(name, 'gi'), function(word) { 
      return '<a href="' + library[name] + '">'+word+'</a>'; 
     }); 
    }; 

    $('#foo ').html(text); 
});​ 
+0

这工作正常,但它会删除所有的HTML标签。另外,如果页面上有更多的div#foos,它们都混合在一起。 – MrEinStain 2012-05-06 13:01:03

0

所有使用的正则表达式我修改了以前的答案失败。这是因为 目标字符串子字符串与替换属性名称不匹配。

该版本通过捕获每个替换字符串并在参数数组中搜索找到的字符串来解决此问题。

function substitute (str) { 'use strict'; 
    var substitutions = { 
     "Stack Overflow": "http://stackoverflow.com", 
     "Wikipedia":  "http://en.wikipedia.org", 
     // ...and so on... 
     }, 
     skeys = Object.keys (substitutions); 

    // build regexp which will capture each match separtely 
    return str.replace (new RegExp ('(' + skeys.join(")|(") + ')', "gi"), function (m0) { 
    // Now scan the arguments array (omitting the last two arugments which 
    // are the source string and match index) 
    for (var ai, i = arguments.length - 2; --i;) { 
     // The index of the argument (less 1) corresponds to the index in skeys of 
     // the name in the substitutions 
     if ((ai = arguments[i])) { 
     return '<a href="' + substitutions[skeys[i - 1]] + '">' + ai + '</a>'; 
     } 
    }  
    return m0;  
    }); 
} 


var str = "You should visit stack overflow. I found it on Wikipedia."; 

// check in console log that links are correctly built. 
console.log (substitute (str)); 
document.write (substitute (str)); 

见的jsfiddle:http://jsfiddle.net/NmGGN/