текст текст текст текст [id1|Павел Дуров] текст текст текст текст 

or

 текст текст текст текст [club123456|Звукозапись] текст текст текст текст 

Tell me how to replace it with JS:

 текст текст текст текст <a href="http://vk.com/club123456">Звукозапись</a> текст текст текст текст 

In essence, a regular session that, through this f-tion, searches for both words and substitutes them:

 str = "aaa aaa aaa aa [club123456|Клуб любителей] ааа ааа ааа"; str.replace(/первая и вторая строка/, function(found) { if (found[found.length - 1] == "|") { return "<a href='http://vk.com/'" + found + ">" } else { return found + "</a>"; } }) console.log(str); 

    1 answer 1

    You can use the following regular expression / /\[(.+?)\|(.+?)]/g

     document.body.innerHTML = "aaa aaa aaa aa [club123456|Клуб любителей] ааа ааа [id1|Павел Дуров] ааа".replace(/\[(.+?)\|(.+?)]/g, function(_,$1,$2) { return '<a href="http://vk.com/'+$1+'">'+$2+'</a>'; })