请看一下(regex101) regex link
var t = $('#text').text();
$('#cvText').html(t.replace(/\b([A-z']+)\b/ig, '<a href="#">$1</a>')).show();
我用它来捕捉所有单词和撇号。 但这也是删除段落中的新行,我想保留它。
我该怎么做?
THX!
答案 0 :(得分:1)
您可以使用以下代码:
$('#btn').on('click',function(e){
var t = $('#text').text();
console.log(t);
$('#cvText').html(nl2br(t.replace(/\b([A-Z']+)\b/ig, '<a href="#">$1</a>'))).show();
});
function nl2br (str) {
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2');
}
div{ padding:10px; margin:10px; font-family:Arial, Helvetica, sans-serif; font-size:16px; line-height:30px; overflow-y:scroll }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id='text' style="width:500px; height:350px;">
The young woman, is known as the bride and she usually has two or more bridesmaids to hold her train. Her partner is called the groom and he is accompanied by the best man, who is usually his best friend. His main tasks are to get his friend to the ceremony sober and on time; to look after the ring(s); and to give a humorous speech later on, which is often designed to gently embarrass his friend.
Traditionally the principal men wear red carnations in their buttonholes, while the rest wear white ones. At the beginning of the church ceremony it is customary for the young woman's father to walk her down the aisle, to the accompaniment of organ music. The central, most important part of the ceremony is when the couple exchange their wedding vows.
At the end of the ceremony the guests leave while the couple and their witnesses sign the marriage register. When the couple come out of the ceremony, the guests often throw confetti (small pieces of coloured paper) at them. Then the couple together with their guests go to the reception. This can be held in a hotel, or sometimes in a marquee (a large tent) in a large garden. In the evening the young couple disappear to get changed into their going away clothes, before setting off for their honeymoon.
</textarea>
<br /><br />
<input type="button" id="btn" value="Convert" />
<div id="cvText" style="border:1px solid #000; width:500px; hei1ght:350px; display:none;"></div>
nl2br
函数会在所有换行符<br />
,<br>
,\r\n
和\n\r
之前插入\n
或\r
)。
该功能的核心是.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2');
。正则表达式匹配并捕获组1中的一个可选符号,该符号不是>
或\r
或\n
。然后,它匹配1个单行换行并将其捕获到组2.替换包括第一个捕获组,<br />
和第二个捕获的文本(换行符)。