3

I am writing some javascript for my website.

I would like to be able to turn (using javascript) specific names into links.

for example, given the name Benjamin it would turn :

Hello my name is Benjamin

into

Hello my name is <a href='something'>Benjamin</a>

The trick is, I don't know what names I need to convert in advance, I receive those in an ajax response. Also, I need to be able to handle stuff along the lines of

<b>B</b>enjam<b>in</b>

while not touching stuff like

B<br />enja<br />min

I would like to know what would be the best practice for designing something able to do this sort of parsing. If there is a ready solution that would probably be better.

Thanks in advance for the help

4

2 回答 2

1

Apply this to your text:

.replace(new RegExp("Benjamin".split('').join(".*?"),"g"),'<a href="#">$&</a>')
                  //    ^------------------------ word to be replaced

Live demo

于 2012-07-23T13:12:07.257 回答
0

This Regex matches all those Names, this way:

var str1 = "Hello Im Benjamin";
var str2 = "Hello Im <b>Benjamin</b>";
var str3 = "Hello Im <b>Benj<b>amin</b></b>"
var str4 = "Hello Im <br>Benjamin< />"    

console.log(str1.match(/ (?:(?:<b>)?[^><\s]?(?:<\/b>)?)*$/)); //[" Benjamin"] 
console.log(str2.match(/ (?:(?:<b>)?[^><\s]?(?:<\/b>)?)*$/)); //[" <b>Benjamin</b>"] 
console.log(str3.match(/ (?:(?:<b>)?[^><\s]?(?:<\/b>)?)*$/)); //[" <b>Benj<b>amin</b></b>"] 
console.log(str4.match(/ (?:(?:<b>)?[^><\s]?(?:<\/b>)?)*$/)); //null
​

Fiddle

于 2012-07-23T14:14:38.160 回答