JSFiddle - React, Tailwind, and code Playground
HTML
<textarea type="text" id="keyword" class="box" value="">#yes #we #can</textarea>
<div id="clone" class="box"></div>
<button id="btn">clone</button>
CSS
.box {
border: 1px solid black;
padding: 5px;
border-radius: 5px;
resize: none;
height: 100px;
width: 200px;
white-space: pre-wrap;
font-family: unset;
}
span {color:blue;}
JavaScript
function hash(str) {
// ・文字列がtextarea先頭の場合、直前のスペースは不要
// ・文字列がtextarea末尾の場合、直後のスペースは不要
// の処理を簡単にするために前後に半角スペースを入れる
const haystack = ` ${str} `;
// タグの開始直前に許容する記号の一覧
const prefixChars = ['、', '。'];
// const reg = new RegExp(`([ ${prefixChars.join('')}])([##].+?)([ ])`, 'g');
// ↓ reg を次に修正
const reg = new RegExp(`([ \r\n|${ prefixChars.join('')}])([##].+?)([ \r\n])`, 'g');
const replaced = haystack.replace(reg, (match, prefix, tagging, suffix) => `${prefix}<span class="tag">${tagging}</span>${suffix}`);
$('#clone').html(replaced.substring(1, replaced.length - 2));
}
$( '#btn' ).click( function(){
hash( $( '#keyword' ).val() );
});