Given a string like this "HowToMakeALiving", I want to split it and make it as "How to make a living". Another situation is "howToMakeALiving", so the first word "how" does not start with capital letter while other words start with capital and I still want to split it and generate "How to make a living"
There are some questions in the community, but they are rarely JS related or need to use packages, and their situation is more complicated, the given string is all lowercase.
So the question is how can I do that by regex in Javascript or any other better method?
CodePudding user response:
You could use a regular expression:
function splitWords(s) {
return s.match(/.[^A-Z]*/g).map((word, i) =>
(i ? word[0].toLowerCase() : word[0].toUpperCase()) word.slice(1)
).join(" ");
}
let words = splitWords("howToMakeALiving");
console.log(words);
words = splitWords("WhyIHadMyDNATakenInParis");
console.log(words);
The regular expression looks for any character (.
) followed by a series of non-capital characters. Each find is a word.
The loop distinguishes between the first word (i == 0
) and other words (i
is truthy). The first character of each word is cast to upper case (first word) or lower case (all other words).
Finally, the words are joined together into a phrase by joining them with a space as separator.
Alternative for capitalised abbreviations
If it is needed to capture abbreviations like "DNA" and the personal pronoun "I", you could:
- Make an explicit comparison with "I", such that it is always put as a capital.
- Only break a word when there is at most one more capital following the break -- you can use a regular expression with look-ahead features.
function splitWords(s) {
return s.match(/.([^A-Z] |.*?(?=[A-Z]([^A-Z]|$)|$))/g).map((word, i) =>
(i && word !== "I" && (word.length < 2 || word[1] != word[1].toUpperCase())
? word[0].toLowerCase()
: word[0].toUpperCase()
) word.slice(1)
).join(" ");
}
let words = splitWords("howToMakeALiving");
console.log(words);
words = splitWords("WhyIHadMyDNATakenInParis");
console.log(words);
words = splitWords("iHateHavingADNATestTaken");
console.log(words);
CodePudding user response:
Option 1: You would do this with .match()
build method like this:
let textvalue = 'howToMakeALiving'
let splitdata = textvalue.match(/[A-Z][a-z] |[0-9] /g).join(" ")
console.log(splitdata)
Option 2: You can use string.split()
method also supports regex it can be achieved like this
let textvalue = 'howToMakeALiving'
let splitdata = textvalue.split(/(?=[A-Z])/);
console.log(splitdata)
CodePudding user response:
Try this, it may have a bug or two but it will send you on the right path.
var res = '';
var chars = 'HowToMakeALiving'.split();
var lastChar = '';
for (var i = 0; i < chars.length; i ) {
if (lastChar = '')
lastChar = chars[i];
if (chars[i].toUpperCase() != chars[i] && lastChar.toUpperCase() != lastChar)
res = res ' ';
res = res chars[i];
}
console.log(res)