开发者

regular expression replace with prototype?

开发者 https://www.devze.com 2023-02-15 05:46 出处:网络
I got some html formatted in the following way: [Title|<a class=\"ex开发者_运维问答ternal\" href=\"http://test.com\">http://test.com</a>]

I got some html formatted in the following way:

[Title|<a class="ex开发者_运维问答ternal" href="http://test.com">http://test.com</a>]

From these texts I'd like to create links using "Title" as the text and "http://test.com" as link. How can I best do this in prototype?


Pure RegExp:

var ProperLink=WierdString.replace(/\[([^|]+)\|(<[^>]+>)[^<]+[^\]]+\]/,'$2$1</a>')

in the context you provided:

function convert(id){
    $(id).innerHTML=$(id).innerHTML.replace(/\[([^|]+)\|(<[^>]+>)[^<]+[^\]]+\]/g,'$2$1</a>');
}
convert('testdiv');


Here is a regex that will retain the original attributes of the anchor tag while doing the replacement:

var link = "[Title|<a class=\"external\" href=\"http://test.com\">http://test.com</a>]";
var pattern = /\[([^|]+)\|([^>]+.?)[^<]*(<\/a>)\]/;
link.replace(pattern, "$2$1$3"));

The output is:

<a class="external" href="http://test.com">Title</a>


Without prototype: http://jsfiddle.net/JFC72/ , you can use prototype to make it simpler.

var myStr = "[THIS IS TITLE|http://test.com]";
document.getElementById('testdiv').innerHTML =  getLink(myStr);


function getLink(myStr)
{
var splitted = myStr.split("|http");
var title = splitted[0].substring(1);
var href = splitted[1].substring(0,splitted[1].length-1);
return "<a href='http" + href + "'>" + title + "</a>";

}


var dummyDiv = document.createElement('div');
dummyDiv.innerHTML = '[Title|<a class="external ...';

var parts = dummyDiv.innerText.slice(1, -1).split('|');
// parts[0] is the text, parts[1] is the URL
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号