UPDATE 1:
Really sorry about this, I just realised I made a mistake with the question.
If data
= some @text1 here, and @text2 here
It should become
some <a href="http://www.google.com/?q=text1">@text1</a> here, and <a href="http://www.google.com/?q=text2">@text2</a> here
ORIGINAL QUESTION:
Using jQuery AJAX, I am returning data
and outputting it like this:
$('.class_name_here').append( data )
Within data
I want to be able to search for certain characters, then add urls to them before outputting them, e.g.
lets say data
contains
some @test here
I want to find the word which follows after @
and add http://www.google.com
to it, so I end开发者_Python百科 up with
some <a href="http://www.google.com">@test</a> here
var str = 'test @google test';
str = str.replace(/(@\w+)/g,'<a href="http://google.com/">$1</a>');
alert(str);
Should work, a simple regex replace. And a nice demo can be found here.
Update:
Try this on for size:
// 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()
That will wrap all @keywords
in a <a href="http://google.com/?q=keywords">@keywords</a>
, for instance.
Demo of this, too
In response to your updated question. Again, this is mostly a slightly modified repeat of a previous answer I gave:
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"
精彩评论