JavaScript

javascript 문단 생성하기

martinooo 2023. 3. 2. 12:27
728x170


javascript 활용해서 더미 문단을 만드는 기능을 구현했다. 

프로젝트시 무작위 문단 or 문장이 필요할 경우에 활용하면 좋다. 


 


 

Github Source ☝ 구현 소스를 보실수 있습니다.

https://github.com/yoogukhyeon/vanilla_javascript

 

GitHub - yoogukhyeon/vanilla_javascript

Contribute to yoogukhyeon/vanilla_javascript development by creating an account on GitHub.

github.com


 

1. 필요한 dom 찾는다. 

2. form submit event 만든다. 

3. input 값을 parseInt 숫자로 변환 

4. switch문을 활용해서 예외처리 

5. text 배열을 slice, sort 활용해서 데이퍼 파싱 

6. 파싱한 배열 데이터를 map, join 활용해서 한번더 파싱 

7. 파싱한 데이터를 UI에 그린다. 

 

// text 배열
const text = [
    `Jelly sweet roll jelly beans biscuit pie macaroon chocolate donut. Carrot cake caramels pie sweet apple pie tiramisu carrot cake. Marzipan marshmallow croissant tootsie roll lollipop. Cupcake lemon drops bear claw gummies. Jelly bear claw gummi bears lollipop cotton candy gummi bears chocolate bar cake cookie. Cupcake muffin danish muffin cookie gummies. Jelly beans tiramisu pudding. Toffee soufflé chocolate cake pastry brownie. Oat cake halvah sweet roll cotton candy croissant lollipop. Macaroon tiramisu chocolate bar candy candy carrot cake jelly sweet. Gummies croissant macaroon dessert. Chocolate cake dragée pie.`,
    `Next level tbh everyday carry, blog copper mug forage kitsch roof party pickled hammock kale chips tofu. Etsy shoreditch 8-bit microdosing, XOXO viral butcher banh mi humblebrag listicle woke bicycle rights brunch before they sold out ramps. Twee shabby chic taiyaki flannel, enamel pin venmo vape four loko. Hexagon kale chips typewriter kitsch 8-bit organic plaid small batch keffiyeh ethical banh mi narwhal echo park cronut.`,
    `Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit​​, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.`,
    `Cat gets stuck in tree firefighters try to get cat down firefighters get stuck in tree cat eats firefighters' slippers kitty power ignore the squirrels, you'll never catch them anyway for what a cat-ass-trophy! or purr as loud as possible, be the most annoying cat that you can, and, knock everything off the table. Pretend you want to go out but then don't bite off human's toes, yet disappear for four days and return home with an expensive injury; bite the vet so catch eat throw up catch eat throw up bad birds. `,
    `This opera's as lousy as it is brilliant! Your lyrics lack subtlety. You can't just have your characters announce how they feel. That makes me feel angry! Anyhoo, your net-suits will allow you to experience Fry's worm infested bowels as if you were actually wriggling through them.
             I just told you! You've killed me! Fry! Quit doing the right thing, you jerk! Michelle, I don't regret this, but I both rue and lament it. Morbo can't understand his teleprompter because he forgot how you say that letter that's shaped like a man wearing a hat.`,
    `Airedale hard cheese mozzarella. Pecorino melted cheese port-salut emmental babybel cheese and wine melted cheese manchego. Everyone loves blue castello everyone loves fromage cheese slices airedale cheddar cream cheese. Bavarian bergkase who moved my cheese halloumi port-salut gouda jarlsberg ricotta rubber cheese. Stinking bishop smelly cheese brie.`,
    `Salvia glossier subway tile, leggings mustache YOLO semiotics chia. Pitchfork tbh af blog church-key meggings vaporware PBR&B master cleanse post-ironic man bun pabst mustache letterpress synth. Snackwave raw denim godard, 3 wolf moon shaman offal kitsch unicorn live-edge selvage schlitz fashion axe vaporware drinking vinegar prism. Shabby chic tacos artisan, chambray chicharrones cardigan leggings typewriter af pop-up williamsburg meditation PBR&B viral. You probably haven't heard of them DIY jean shorts subway tile fashion axe bushwick kitsch tumeric cloud bread vaporware freegan franzen pork belly chicharrones banh mi.`,
    `Man braid celiac synth freegan readymade, pitchfork fam salvia waistcoat lomo bitters gentrify four loko. Pitchfork semiotics post-ironic vegan. Tofu meditation microdosing hashtag semiotics venmo. Flexitarian vape tilde taiyaki. Prism poutine farm-to-table, messenger bag vegan taxidermy tattooed sartorial squid jean shorts fixie selvage trust fund vape.`,
    `Rutters Plate Fleet boom chandler Brethren of the Coast handsomely lookout marooned brigantine knave. Buccaneer gangway jack rum loot spyglass line Jack Tar fore gaff. Gaff topmast scuttle ballast swab draught measured fer yer chains dance the hempen jig Chain Shot yardarm.`,
];

const form = document.querySelector('.form');
const amount = document.getElementById('amount');
const result = document.querySelector('.text');

form.addEventListener('submit', (e) => {
    e.preventDefault();
    //문자열을 숫자롤 변환
    let value = parseInt(amount.value);

    //switch 예외 처리
    switch (true) {
        case isNaN(value): //숫자가 아닐 경우
            alert('숫자를 입력해주세요.');
            amount.value = '';
            amount.focus();
            return; //조건 해당시 종료
        case value < 1: //값이 음수일 경우
            alert('음수값을 입력하실수 없습니다!');
            amount.value = '';
            amount.focus();
            return; //조건 해당시 종료
        case value > 9: //값이 9개 이상일 경우
            alert('9개 이상의 문단을 입력하실수 없습니다!');
            amount.value = '';
            amount.focus();
            return; //조건 해당시 종료
    }

    //switch 조건 통과시 무작위 text값 생성
    //slice 활용해서 value 만큼 배열을 짜르고 sort 함수로 무작위 정렬을 한다.
    let tempText = text.slice(0, value).sort(() => Math.random() - 0.5);

    //map을 순회해서 dom을 만들고 해당 값을 넣고 join 문자열로 만든다.
    tempText = tempText
        .map((item) => {
            return `<p class="result">${item}</p>`;
        })
        .join('');

    //파싱한 데이터를 UI를 그린다.
    result.innerHTML = tempText;
});
그리드형