Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在关键字之前添加字符串-javascript_Javascript_Regex_String_Search - Fatal编程技术网

在关键字之前添加字符串-javascript

在关键字之前添加字符串-javascript,javascript,regex,string,search,Javascript,Regex,String,Search,我有一个论坛,我想自动解析一些主要链接。例如,如果用户发表如下帖子: "You should visit &StackOverflow. I found it on Wikipedia." var linkArray = [ ["StackOverflow", "http://www.stackoverflow.com/", "Description"], ["Wikipedia", "http://wikipedia.org/", "Free en

我有一个论坛,我想自动解析一些主要链接。例如,如果用户发表如下帖子:

"You should visit &StackOverflow. I found it on Wikipedia."
var linkArray = [ ["StackOverflow", "http://www.stackoverflow.com/", "Description"],
                  ["Wikipedia", "http://wikipedia.org/", "Free encyclopedia"] ];
你应该访问StackOverflow。我在维基百科上找到的

它会像这样自动解析它:

"You should visit &StackOverflow. I found it on Wikipedia."
var linkArray = [ ["StackOverflow", "http://www.stackoverflow.com/", "Description"],
                  ["Wikipedia", "http://wikipedia.org/", "Free encyclopedia"] ];
你应该去看看。我在车上找到的

仅使用JavaScript就可以做到这一点吗


感谢您的帮助。:-)

如果您正在预处理文本,则可以将函数与a一起使用,并使用替换的正则表达式:

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>';
});
|

是,使用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>");
除非是这样写的,否则不应替换为链接:

"You should visit &StackOverflow. I found it on Wikipedia."
var linkArray = [ ["StackOverflow", "http://www.stackoverflow.com/", "Description"],
                  ["Wikipedia", "http://wikipedia.org/", "Free encyclopedia"] ];
然后,您的方法只需要添加特殊符号

此外,我将数据放在如下数组中:

"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);
}
函数添加链接(textInput){

对于(var i=0;i您想要创建一个干净且可扩展的代码是创建一个word=>link库,然后您可以迭代该库并在代码内部进行替换

这里有一个小提琴演示

$(函数(){
var text=$('#foo').text(),
图书馆={
堆栈溢出:'http://stackoverflow.com',
维基百科:'http://wikipedia.com'
},
名称
for(库中的名称){
text=text.replace(新的RegExp(名称,'gi')、函数(word){
返回“”;
});  
};
$('#foo').html(文本);
});​

如果目标 字符串包含按大小写不同的替换字符串的变体。这是因为 目标字符串替换字符串与替换属性名称不匹配

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

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));
函数替换(str){'use strict';
变量替换={
“堆栈溢出”:http://stackoverflow.com",
“维基百科”:http://en.wikipedia.org",
//……等等。。。
},
skeys=Object.keys(替换);
//构建regexp,它将分别捕获每个匹配项
返回str.replace(新的RegExp(“(”+skeys.join(“)|(“+”)”),“gi”),函数(m0){
//现在扫描arguments数组(省略最后两个
//是源字符串和匹配索引)
for(var ai,i=arguments.length-2;--i;){
//参数的索引(小于1)对应于
//替换中的名称
if((ai=参数[i])){
返回“”;
}
}    
返回m0;
});
}
var str=“您应该访问堆栈溢出。我在维基百科上找到了它。”;
//在控制台日志中检查链接是否正确构建。
console.log(替换(str));
书面文件(替换(str));

请参阅JSFIDLE:

您是在将文本放入DOM之前对其进行预处理,还是在文本在DOM中已就绪后添加这些链接?这不是简单地用其他单词替换单词吗?有一个类似于StackOverflow的问题:这不太理想,因为您必须定义两次关键字。有吗这绝对是一个更好的方法。@YMMD:你不必这么做,你可以做我以前做过的事情,从一个哈希开始,动态构建正则表达式。我将添加一个示例。编辑DoneTo对我来说,这似乎更好。:-)感谢您更新您的答案!当我尝试使用JSFIDLE时,如果我使用小写堆栈溢出,则链接是未定义的。“gi”标志应该使regexp不区分大小写。我想知道发生了什么。@HeitorChang:谢谢您提到这一点。它不起作用的原因是
替换
中的键区分大小写,即使regular表达式不是。我已经修复了示例(并添加了一个实时示例)。这可以正常工作,但它会删除所有HTML标记。此外,如果页面上有更多的div#foo,它们会混合在一起。