在字符串中搜索值,然后更新字符串

时间:2011-06-29 14:55:25

标签: javascript jquery

更新1:

真的很抱歉,我刚才意识到我在这个问题上犯了错误。

如果data = some @text1 here, and @text2 here

它应该成为

some <a href="http://www.google.com/?q=text1">@text1</a> here, and <a href="http://www.google.com/?q=text2">@text2</a> here

原始问题:

使用jQuery AJAX,我将返回data并输出如下:

$('.class_name_here').append( data )

data内,我希望能够搜索某些字符,然后在输出之前添加网址,例如。

让我们说data包含

some @test here

我想找到@之后的字词,并在其中添加http://www.google.com,所以我最终会

some <a href="http://www.google.com">@test</a> here

2 个答案:

答案 0 :(得分:4)

var str = 'test @google test';
str = str.replace(/(@\w+)/g,'<a href="http://google.com/">$1</a>');
alert(str);

应该工作,一个简单的正则表达式替换。还有一个很好的演示can be found here

更新

尝试使用此尺寸:

// place somewhere in global scope (in head of document for instance)
String.prototype.addGoogleLinks = function(){
    return this.replace(/(@(\w+))/g,'<a href="http://google.com/?q=$2">$1</a>');
};

// reference the data variable and call the addGoogleLinks()
// which will return the formatted string
data.addGoogleLinks()

例如,这会将所有@keywords包装在<a href="http://google.com/?q=keywords">@keywords</a>中。

Demo of this, too

答案 1 :(得分:1)

回复您的更新问题。同样,这主要是我给出的previous answer的略微修改的重复:

function googlify(text) {
  return text.replace(/@(\w+)/g,
                      "<a href=\"http://www.google.com/?q=$1\">@$1</a>");
}

alert(googlify("some @text1 here, and @text2 here"));
// Alerts "some <a href="http://www.google.com/?q=text1">@text1</a> here,
//         and <a href="http://www.google.com/?q=text2">@text2</a> here"
相关问题