JSFiddle - React, Tailwind, and code Playground
HTML
<textarea type="text" id="keyword" class="box" value="">#hello world #yes we #can</textarea>
<div id="clone" class="box"></div>
<button id="btn">clone</button>
<p>
問題<br>
➀改行を入れても1つのタグとして取得してしまう。<br>
➁取得できたタグのうち最後のものにしかspanがつかない。<br>
➂最後の#canが取得できない。
</p>
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 ){
var regexp = new RegExp( /#+[^ ]+(\s| )/ );
var result = regexp.test( str );
if ( regexp.test( str ) ) {
// 取得
var tags = str.match( /#+[^ ]+(\s| )/g );
console.log( 'tags;', tags );
// タグにspanをつけて全文をコピー
tags.forEach(function( value ) {
if ( str.match( value ) ) {
var target = str.match( value );
console.log( 'target:',target );
var span = '<span class="tag">' + target + '</span>';
var replaced = str.replace( target, span );
$( '#clone' ).html( replaced );
}
});
}else{
$( '#clone' ).html( str );
}
}
$( '#btn' ).click( function(){
hash( $( '#keyword' ).val() );
});