본문 바로가기

퍼블리싱/javascript&jQuery

[jquery]반복문을 이용해 문자열 자르기 split()

어떤 텍스트의 스타일을 수정하고싶은데, 텍스트가 모두 통으로 들어가 있어서 css를 적용하기가 힘들어서 텍스트를 나눠서 가지고 오는 방법을 찾아봤다.

 

문제특징 

01. 반복되는 구조를 가지고 있다. ( li가 3번 반복되는 구조)

02. 텍스트가 하나의 태그에 모두 들어가 있다.

03. 텍스트가 공통된 구조로 되어있다. 

 

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<ul class="boxWrap">
    <li class="m01">
        What is Lorem Ipsum?
        Lorem Ipsum is simply dummy
        A. Lorem Ipsum is simply dummy
        B. text of the printing 
        C. and typesetting industry.
    </li>
    <li class="m01">
        Why do we use it?
        It is a long established
        A. It is a long established
        B. fact that a reader will be distracted
        C. by the readable content of
    </li>
    <li class="m01">
        Where does it come from?
        Contrary to popular belief,
        A. Contrary to popular belief,
        B. Lorem Ipsum is not simply 
        C. random text.
    </li>
</ul>
cs

 

해결 방법

01. 반복문으로 태그의 텍스트를 가지고 온다.

02. 엔터로 텍스트를 분리한다 

     - .split() : 문자열 분리

     - \n 또는 \\n: 엔터를 나타내는 정규식 

03. 배열로 저장된 텍스트에 앞뒤로 태그를 붙여 텍스트를 변경해준다. 

 

JQUERY

 

1
2
3
4
5
6
7
8
9
10
11
12
$('ul').find('li.m01').each(function(i, e){ // 각 태그마다 반복 실행
    var ALLTXT = $(this).text(); //각각의 텍스트값을 저장
    var split_txt = ALLTXT.split('\n'); //엔터를 기준으로 나눈다.
    // 배열로 저장된다. 
 
    var newTXT = '<p class="txt01">' + split_txt[0+ '</p><p class="txt02">' + split_txt[1+ '</p><p class="txt03">' + split_txt[2]  + '</p><p class="txt04">' + split_txt[3]  + '</p><p class="txt05">' + split_txt[4+ '</p>'
    // 한줄씩 태그로 분리
 
    $(this).html(newTXT);
   // newTXT를 li.m01안에 새로 넣음
 
});
 
cs

 

이렇게 하면 
한줄씩 태그가 분리된다. 

개발자모드에서 확인!