我試圖找到一個字符串中的特定文本,如果發現它包含在一個鏈接。如何將特定文本轉換爲超鏈接?
我正在尋找的文本的格式爲:
號|字母| 4張隨機數
實施例:7Q3847
使用jQuery我能找到一個例如(其中,隨機數是硬編碼的),併成功地將它轉換成一個鏈接。這是我到目前爲止的代碼:
$('.text').each(function(){
var code = '7Q2992';
code = code.replace(/\W/g, '');
var str = code.split(" ");
var link = $(this).text();
text = link.replace(str, "<a href='https://www.google.ie/?gws_rd=cr&ei=4j6LWLm4DcbYU6-KvZgB#safe=active&q=" + code + "'>" + str + "</a>");
$(this).html(text);
});
我想要什麼,而不是,是有VAR code
能夠搜索開始與7Q或7T任何文字...
我將不勝感激任何幫助!
FULL SNIPPET
$('.text').each(function() {
var code = '7Q2992';
code = code.replace(/\W/g, '');
var str = code.split(" ");
var link = $(this).text();
text = link.replace(str, "<a href='https://www.google.ie/?gws_rd=cr&ei=4j6LWLm4DcbYU6-KvZgB#safe=active&q=" + code + "'>" + str + "</a>");
$(this).html(text);
});
body {
width: 580px;
margin: 50px auto 0;
font-family: sans-serif;
font-size: 16px;
}
.output {
float: left;
}
.ideal {
float: right;
}
header {
color: white;
padding: 10px;
}
.red {
background: red;
}
.green {
background: green;
}
p {
line-height: 1.5;
}
a {
text-decoration: none;
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output">
<header class="red">Current output</header>
<p class="text">
Text containing letters 7Q2992
</p>
<p class="text">
Text containing letters 7T3940
</p>
<p class="text">
Text containing letters 7Q3940
</p>
</div>
<div class="ideal">
<header class="green">Desired output</header>
<p>
Text containing letters
<a href="https://www.google.ie/?gws_rd=cr&ei=4j6LWLm4DcbYU6-KvZgB#safe=active&q=7Q2992">7Q2992</a>
</p>
<p>
Text containing letters <a href="https://www.google.ie/?gws_rd=cr&ei=4j6LWLm4DcbYU6-KvZgB#safe=active&q=7T3940">7T3940</a>
</p>
<p>
Text containing letters <a href="https://www.google.ie/?gws_rd=cr&ei=4j6LWLm4DcbYU6-KvZgB#safe=active&q=7Q3940">7Q3940</a>
</p>
</div>
良好的解決方案+1 –
這工作得很好,我喜歡更新URL的簡單性。非常感謝 – sol