2016-02-01 2 views
0

У меня есть html-страница, теперь я показываю строку, содержащую текст, начинающийся с '@'. Что мне нужно сделать, это заменить все тексты в строку, начиная с «@» с помощью тега привязки Использование JavaScript что-то вродеЗаменить текст, начинающийся с @ с тегом привязки

Eg:

Моя строка:

отлично провели время с @ sarah333 и @ kevin0955 на пляже.

Требуемая мощность:

had a great time with <a href="http://example.com/sarah333">@sarah333</a> and <a href="http://example.com/kevin9099">@kevin9099</a> at beach. 
+2

И Что вы пытались получить этот вывод? – dikesh

+0

var wordsBegginingWithAt = text.split ('') .filter (function (word) {return word [0] === '@';}). ForEach (function (word) {text.replace (word, ''+word+'')}); текст. – Loupax

ответ

3

Попробуйте

str = 'had a great time with @sarah333 and @kevin0955 at beach.'; 
replacedStr = str.replace(/\s\@(.*?)(\s|$)/g, ' <a href="http://example.com/$1">@$1</a>$2'); 
-2
<html> 
<head> 
<script> 
function CreateInput(event) { 
    var key = event.keyCode; 
    var tbl=document.getElementById("tbl"); 
    var str = "had a great time with @sarah333 and @kevin0955 at beach."; 

    replacedStr = str.replace(/\s\@(.*?)(\s|$)/g, ' <a href="http://example.com/$1">$1</a>$2'); 

    if(key == 13) 
    { 
    tbl.innerHTML += replacedStr; 
    } 
} 
</script> 
</head> 
<body onKeypress="CreateInput(event)"> 
<table id="tbl"> 
</table> 
</body> 
</html> 
+0

Вы пытаетесь использовать этот код? – Grundy

+0

да, я пробовал это –

+0

, и вы получаете 'Требуемый вывод:' из вопроса? – Grundy

0

В Php

$str = "had a great time with @sarah333 and @kevin0955 at beach"; 
$str = preg_replace('/\B\@([a-zA-Z0-9_]{1,})/', '<a href="http://example.com/$1" class="primary-black">$0</a>', html_entity_decode($str)); 
echo $str; 

В Javascript

var str = "had a great time with @sarah333 and @kevin0955 at beach"; 
str = str.replace(/@(\w*[a-zA-Z_]+\w*)/gim, '<a class="primary-black" href="http://www.google.com/$1">$1</a>'); 
+1

в тегах - javascript, а не php – Grundy

+0

У меня есть править как php, так и javascrip – areeb

1

Еще один способ

document.getElementById('r').innerHTML = 'Result: ' + 
 
    'had a great time with @sarah333 and @kevin0955 at beach.'.replace(/@(\w+)/g, '<a href="http://example.com/$1">@$1</a>');
<div id='s'>Source: had a great time with @sarah333 and @kevin0955 at beach.</div> 
 
<div id='r'></div>

Смежные вопросы