如何用JavaScript的charAt()实现字符搜索统计及结果展示功能?
Solution to Build a Character Counter with
charAt() and window.open() Got it, let's put this together! Below is a fully functional implementation that does exactly what you need—with clear breakdowns for each key part.
HTML Structure
First, we'll set up a clean form with all the elements we need for input and output:
<form id="charCounterForm"> <div> <label for="inputText">Enter your multi-line text:</label><br> <textarea id="inputText" rows="8" cols="50" placeholder="Type your text here..."></textarea> </div> <div style="margin: 15px 0;"> <label for="searchChar">Character to search for:</label><br> <input type="text" id="searchChar" maxlength="1" placeholder="e.g., x"> </div> <div> <button type="button" id="countBtn">Count Occurrences</button> </div> <div style="margin-top: 15px;"> <label for="result">Result:</label><br> <textarea id="result" rows="2" cols="50" readonly></textarea> </div> </form>
JavaScript Logic
Now add the script to handle the counting, validation, and result display:
document.getElementById('countBtn').addEventListener('click', function() { // Grab user input values, trim extra whitespace const inputText = document.getElementById('inputText').value.trim(); const searchChar = document.getElementById('searchChar').value.trim(); // Quick validation to avoid edge cases if (!inputText) { document.getElementById('result').value = 'Please enter some text first!'; return; } if (!searchChar || searchChar.length > 1) { document.getElementById('result').value = 'Please enter a single character to search!'; return; } let count = 0; // Loop through each character using charAt() for (let i = 0; i < inputText.length; i++) { if (inputText.charAt(i) === searchChar) { count++; } } // Handle the final result if (count === 0) { // Open new window with the error message const errorWindow = window.open('', '_blank', 'width=400,height=200'); errorWindow.document.write('<h3>Search Result</h3>'); errorWindow.document.write('<p>未在文本中找到搜索字符</p>'); errorWindow.document.close(); document.getElementById('result').value = ''; } else { document.getElementById('result').value = `The character "${searchChar}" appears ${count} time(s).`; } });
Key Details Explained
- Using
charAt(): We loop through every index of the input text string, andcharAt(i)pulls the character at positioni. We compare this to our target character and increment the count each time there's a match—exactly what you asked for. - Input Validation: We added checks to make sure the user enters text and a single search character, which prevents weird bugs (like searching for an empty string).
window.open()for No Matches: When the count hits 0, we open a small new window and write the error message directly into it. The_blankparameter ensures it opens in a new tab/window, and we set dimensions to keep it tidy.- Result Display: If matches are found, we show the count in a readonly textarea so the user can easily see or copy the result.
内容的提问来源于stack exchange,提问作者Moodi
相关产品推荐
相关产品推荐

