[svelte]TextParser

박민규·2020년 11월 3일
<script>
	export let contents;
	export let textId;
	
	let trackingUrl = /(http(s)?:\/\/|www.)([a-z0-9\w]+\.*)+[a-z0-9]{2,4}([\/a-z0-9-%#?&=\*@\w])+(\.[a-z0-9]{2,4}(\?[\/a-z0-9-%#?&=\*@\w]+)*)*/gi;
	
	let trackingTag = /(#[\d|A-Z|a-z|ㄱ-ㅎ|ㅏ-ㅣ|가-힣|\_]*)/gi;
	
	const parseText = (txt) => {
		txt = txt.replaceAll(trackingTag, function(x){
			return `*-*${x}*-*`
		});
		txt = txt.replaceAll(trackingUrl, function(x){
			return x.replaceAll('*-*', '')
		});
 		txt = txt.replaceAll(trackingUrl, function(x){
			return `*-*${x}*-*`
		});
		
		txt = txt.split('\n');
		for (let i=0; i<txt.length; i++) {
			txt[i] = txt[i].split('*-*');
		}
		
		console.log(txt)
		return txt
		
	}
	
	const alertTag = (ttt) => {
		window.alert(ttt);
	}
	
	
</script>

{#if contents}
	<h1>{textId}</h1>
	{#each parseText(contents) as paragraph }
		<p>
			{#each paragraph as item}
				{#if (item.match(trackingTag)) && (item[0] === '#')}
					<span on:click={()=>alertTag(item)}>{item}</span>
				{:else if item.match(trackingUrl)}
					<a href={item}>{item}</a>
				{:else}
					{item}
				{/if}
			{/each}
		</p>
	{/each}
{/if}

<style>
	h1 {
		margin-top: 50px;
	}
	
	p {
		font-size: 15px;
		line-height: 20px;
		margin-bottom: 20px;
		padding-top: 1px;
		
		font-family: 'Noto Sans KR', sans-serif;
		box-sizing: border-box;
	}
	
	p a {
		color: red;
		text-decoration: none;
		transition: 0.2s all;
	}
	
	p a:hover {
		color: grey;
	}
	
	p span {
		color: blue;
	}

</style>

텍스트에 http,#tag가 있을경우 http는 해당 링크로 #tag는 해당 태그를 띄우는
컴포넌트다.

number 형식 textId를 props로 받아서 각 문단의 넘버를 보여주고
text 형식인 contents를 props로 받아왔는데
contents text의 https:와 #Tag를 각각의 배열로 나누고 https:와 #Tag앞에 태그를 넣기 위해서 parseText를 만들었다.

#tag 클릭 이벤트를 처리하는데,alertTag를 호출한다.

css를 이용하여 https와 #Tag에 색상을 넣어준다.

trackingUrl,trackingTag는 각각 http주소,#tag를 찾는 정규표현식이다.

profile
개(발)초보

0개의 댓글