Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  186] [ 3]  / answers: 1 / hits: 98407  / 14 Years ago, wed, november 10, 2010, 12:00:00

I’ve been trying to get a JavaScript regex command to turn something like thisString into This String but the closest I’ve gotten is replacing a letter, resulting in something like Thi String or This tring. Any ideas?



To clarify I can handle the simplicity of capitalizing a letter, I’m just not as strong with RegEx, and splitting somethingLikeThis into something Like This is where I’m having trouble.


More From » regex

 Answers
66
thisStringIsGood
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })


displays



This String Is Good




(function() {

const textbox = document.querySelector('#textbox')
const result = document.querySelector('#result')
function split() {
result.innerText = textbox.value
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, (str) => str.toUpperCase())
};

textbox.addEventListener('input', split);
split();
}());

#result {
margin-top: 1em;
padding: .5em;
background: #eee;
white-space: pre;
}

<div>
Text to split
<input id=textbox value=thisStringIsGood />
</div>

<div id=result></div>




[#95013] Monday, November 8, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sonja

Total Points: 541
Total Questions: 113
Total Answers: 114

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
sonja questions
Mon, Nov 30, 20, 00:00, 4 Years ago
Sun, Oct 11, 20, 00:00, 4 Years ago
Thu, May 21, 20, 00:00, 4 Years ago
Sun, Nov 10, 19, 00:00, 5 Years ago
Mon, Aug 26, 19, 00:00, 5 Years ago
;