Problem I get unwanted things with .replaceall - javascript

This function is for getting the link for my subcategories. Now the problem is I console.log() the values and I have the text "hire/indoor--outdoor-activities" which I don't want to have "--" between "indoor" and "outdoor". But if I remove .replaceAll and .replace the text is "Indoor & Outdoor Activities". The problem are the two blank spaces between indoor and & and outdoor and &. Is there a regex or something so I can have only one "-"?
const subcategoryLink = (sector) => {
const sectorLink = `hire/${sector}`
const lowerCaseLink = sectorLink.toLowerCase().replace('&', '').replaceAll(' ', '-')
console.log(lowerCaseLink)
return lowerCaseLink
}
subcategoryLink("Indoor & Outdoor Activities");

You can go ahead and replace any sequence of spaces and '&'s with a single dash using regex
sectorLink.toLowerCase().replaceAll(/[ &]+/g, '-')

const subcategoryLink = (sector) => {
const sectorLink = `hire/${sector}`
const lowerCaseLink =sectorLink.toLowerCase().replace(/\&/g, '').replace(' ',' ').replace(/ /g,'-');
console.log(lowerCaseLink);
return lowerCaseLink;
}
subcategoryLink("Indoor & Outdoor Activities");

Related

Is there a way to remove a newline character within a string in an array?

I am trying to parse an array using Javascript given a string that's hyphenated.
- foo
- bar
I have gotten very close to figuring it out. I have trimmed it down to where I get the two items using this code.
const chunks = input.split(/\ ?\-\ ?/);
chunks = chunks.slice(1);
This would trim the previous input down to this.
["foo\n", "bar"]
I've tried many solutions to get the newline character out of the string regardless of the number of items in the array, but nothing worked out. It would be greatly appreciated if someone could help me solve this issue.
You could for example split, remove all the empty entries, and then trim each item to also remove all the leading and trailing whitespace characters including the newlines.
Note that you don't have to escape the space and the hyphen.
const input = `- foo
- bar`;
const chunks = input.split(/ ?- ?/)
.filter(Boolean)
.map(s => s.trim());
console.log(chunks);
Or the same approach removing only the newlines:
const input = `- foo
- bar`;
const chunks = input.split(/ ?- ?/)
.filter(Boolean)
.map(s => s.replace(/\r?\n|\r/g, ''));
console.log(chunks);
Instead of split, you might also use a match with a capture group:
^ ?- ?(.*)
The pattern matches:
^ Start of string
?- ? Match - between optional spaces
(.*) Capture group 1, match the rest of the line
const input = `- foo
- bar`;
const chunks = Array.from(input.matchAll(/^ ?- ?(.*)/gm), m => m[1]);
console.log(chunks);
You could loop over like so and remove the newline chars.
const data = ["foo\n", "bar"]
const res = data.map(str => str.replaceAll('\n', ''))
console.log(res)
Instead of trimming after the split. Split wisely and then map to replace unwanted string. No need to loop multiple times.
const str = ` - foo
- bar`;
let chunks = str.split("\n").map(s => s.replace(/^\W+/, ""));
console.log(chunks)
let chunks2 = str.split("\n").map(s => s.split(" ")[2]);
console.log(chunks2)
You could use regex match with:
Match prefix "- " but exclude from capture (?<=- ) and any number of character different of "\n" [^\n]*.
const str = `
- foo
- bar
`
console.log(str.match(/(?<=- )[^\n]*/g))
chunks.map((data) => {
data = data.replace(/(\r\n|\n|\r|\\n|\\r)/gm, "");
return data;
})
const str = ` - foo
- bar`;
const result = str.replace(/([\r\n|\n|\r])/gm, "")
console.log(result)
That should remove all kinds of line break in a string and after that you can perform other actions to get the expected result like.
const str = ` - foo
- bar`;
const result = str.replace(/([\r\n|\n|\r|^\s+])/gm, "")
console.log(result)
const actualResult = result.split('-')
actualResult.splice(0,1)
console.log(actualResult)

Regexp search result hightlight with accent

Can someone help me to improve my search please ? I try to highlight several words when a user write one or many things in the input. I am using this function :
checkHighlightList(originalStr, queries) {
const regexp = new RegExp(queries.join('|'), 'gi');
const matchs = originalStr.match(regexp);
if (matchs) {
const result = originalStr.replace(regexp, match => `<span class="highlight">${ match }</span>`);
return result;
}
}
The problem is, if I have the word "pokémon" in my queries and I write "kemon". It doesn't work because every accent characters are different (ô !== o). I would like to write "ke" or "ké" in my input and highlight the "ké" part in "pokémon". I use some french words who contains a lot of accent on it.
Thank you
To search accented text without accent in the search terms you can define an accent map, and compose a regex from that:
accentMap = {
ae: '(ae|æ|ǽ|ǣ)',
a: '(a|á|ă|ắ|ặ|ằ|ẳ|ẵ|ǎ|â|ấ|ậ|ầ|ẩ|ẫ|ä|ǟ|ȧ|ǡ|ạ|ȁ|à|ả|ȃ|ā|ą|ᶏ|ẚ|å|ǻ|ḁ|ⱥ|ã)',
c: '(c|ć|č|ç|ḉ|ĉ|ɕ|ċ|ƈ|ȼ)',
e: '(e|é|ĕ|ě|ȩ|ḝ|ê|ế|ệ|ề|ể|ễ|ḙ|ë|ė|ẹ|ȅ|è|ẻ|ȇ|ē|ḗ|ḕ|ⱸ|ę|ᶒ|ɇ|ẽ|ḛ)',
i: '(i|í|ĭ|ǐ|î|ï|ḯ|ị|ȉ|ì|ỉ|ȋ|ī|į|ᶖ|ɨ|ĩ|ḭ)',
n: '(n|ń|ň|ņ|ṋ|ȵ|ṅ|ṇ|ǹ|ɲ|ṉ|ƞ|ᵰ|ᶇ|ɳ|ñ)',
o: '(o|ó|ŏ|ǒ|ô|ố|ộ|ồ|ổ|ỗ|ö|ȫ|ȯ|ȱ|ọ|ő|ȍ|ò|ỏ|ơ|ớ|ợ|ờ|ở|ỡ|ȏ|ō|ṓ|ṑ|ǫ|ǭ|ø|ǿ|õ|ṍ|ṏ|ȭ)',
u: '(u|ú|ŭ|ǔ|û|ṷ|ü|ǘ|ǚ|ǜ|ǖ|ṳ|ụ|ű|ȕ|ù|ủ|ư|ứ|ự|ừ|ử|ữ|ȗ|ū|ṻ|ų|ᶙ|ů|ũ|ṹ|ṵ)'
};
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function checkHighlightList(str, queries) {
accentRegex = new RegExp(Object.keys(accentMap).join('|'), 'g');
const queryRegex = new RegExp(queries.map(q => {
return escapeRegExp(q).toLowerCase().replace(accentRegex, m => {
return accentMap[m] || m;
});
}).join('|'), 'gi');
return str.replace(queryRegex, m => `<span class="highlight">${ m }</span>`);
}
let source = 'Pokémon & Crème Brulée';
let result = checkHighlightList(source, [ 'kemon', 'creme' ]);
console.log('source:\n "' + source + '"');
console.log('result:\n "' + result + '"');
Output for search terms [ 'kemon', 'creme' ]:
source:
"Pokémon & Crème Brulée"
result:
"Po<span class="highlight">kémon</span> & <span class="highlight">Crème</span> Brulée"
Explanation of accentRegex:
it is an OR regex of all keys of accentMap:
example: /ae|a|c|e|i|n|o|u/g
tweak the map as needed for additional accent chars
Explanation of queryRegex:
it is an OR regex of all query terms, where each key in accentMap gets mapped to an OR regex of all accented version of that key
example: query term cafe results in this (shortened) regex: /c(a|á|ă|ắ|ặ|ǎ|â|ậ|ä|ȧ|à|)f(e|é|ĕ|ě|ệ|ë|ė|è|ẽ)/gi
Note: Since the query terms are user specified and used in a regex, we need to escape the regex symbols in the user input, hence the use of function escapeRegExp().

Move leading or trailing whitespaces in string out of asterisks

I'm trying to transform invalid markdown for bold words into valid one. For the major part I've figured out how to get the words surrounded by asterisks but now I'm trying to find a way to transform this:
**A bold text **
Into this:
**A bold text**
Moving the trailing whitespace two steps to the right, out of the asterisks.
Same would be needed for leading whitespaces.
Any suggestions? Thanks!
Edit: I'd need to keep the whitespace but outside the bold syntax, not remove it.
let str = '**A bold text **';
let frontSpace = str.match(/\W{1,}/).toString().replace('**','');
let rearSpace = str.match(/\W{2,}$/).toString().replace('**','');
console.log(frontSpace + '**' + str.replace(/\*\*/g,'').trim() + '**' +rearSpace);
You can use the combination of split and trim to build the expected string as shown below.
const word1 = '** Hello Keel **';
const wordArr1 = word1.split('**');
console.log(wordArr1[0] + '**' + wordArr1[1].trim() + '**' + wordArr1[2]);
This would also work for Hello ** Keel **, Welcome to Stack Overflow
You can use replace
\*{2}(\s*)([^*]+?)(\s*)\*{2}
let str = `**A bold text **`
let replacer = (str) => {
return str.replace(/\*{2}(\s*)([^*]+?)(\s*)\*{2}/g, (m, g1,g2,g3) => {
return `${g1}**${g2}**${g3}`
})
}
console.log(replacer(str))
console.log(replacer("some random string ** some text **"))

Hyphen for after 2nd character

I would like to write a simple function to mask an input with a date like 12-2018 (MM-YYYY) and used a regex like below, but its return the number with a slash for every 2 digits. But I am looking only slash with after first 2 digits only. I have searched for a lot and got below hint only.
("122018").match(new RegExp('.{1,2}', 'g')).join("-")
("122018").match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
Your regex should simply specify the exact number of characters in the curly braces. Refer to the capture groups when replacing.
Use '-?' or '.?' to allow an optional (dash or any) delimiter. Or take it out if you do not want to allow delimiters.
You might want to allow for optional spaces around your input too...
let inputValues = ['122018', '12-2018', '2018']
let res = rx = /(\d{2})(\d{4})/
//let res = rx = /(\d{2})-?(\d{4})/
inputValues.forEach(inputValue => {
let m = res.exec(inputValue)
if (m) {
console.warn('good input: ' + inputValue)
//console.log(m[1] + '/' + m[2])
} else {
console.warn('bad input: ' + inputValue)
}
})
date = '122018';
arr = date.match(/^(..)(.+)$/);
res = [arr[1],arr[2]].join('-');
console.log(res);

Convert camelCaseText to Title Case Text

How can I convert a string either like 'helloThere' or 'HelloThere' to 'Hello There' in JavaScript?
const text = 'helloThereMister';
const result = text.replace(/([A-Z])/g, " $1");
const finalResult = result.charAt(0).toUpperCase() + result.slice(1);
console.log(finalResult);
capitalize the first letter - as an example. Note the space in " $1".
Of course, in case the first letter is already capital - you would have a spare space to remove.
Alternatively using lodash:
lodash.startCase(str);
Example:
_.startCase('helloThere');
// ➜ 'Hello There'
Lodash is a fine library to give shortcut to many everyday js tasks.There are many other similar string manipulation functions such as camelCase, kebabCase etc.
I had a similar problem and dealt with it like this:
stringValue.replace(/([A-Z]+)*([A-Z][a-z])/g, "$1 $2")
For a more robust solution:
stringValue.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1")
http://jsfiddle.net/PeYYQ/
Input:
helloThere
HelloThere
ILoveTheUSA
iLoveTheUSA
Output:
hello There
Hello There
I Love The USA
i Love The USA
Example without side effects.
function camel2title(camelCase) {
// no side-effects
return camelCase
// inject space before the upper case letters
.replace(/([A-Z])/g, function(match) {
return " " + match;
})
// replace first char with upper case
.replace(/^./, function(match) {
return match.toUpperCase();
});
}
In ES6
const camel2title = (camelCase) => camelCase
.replace(/([A-Z])/g, (match) => ` ${match}`)
.replace(/^./, (match) => match.toUpperCase())
.trim();
The best string I've found for testing camel-case-to-title-case functions is this ridiculously nonsensical example, which tests a lot of edge cases. To the best of my knowledge, none of the previously posted functions handle this correctly:
__ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D
This should be converted to:
To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D
If you want just a simple function that handles cases like the one above (and more cases than many of the previously answers), here's the one I wrote. This code isn't particularly elegant or fast, but it's simple, understandable, and works.
The snippet below contains an online runnable example:
var mystrings = [ "__ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D", "helloThere", "HelloThere", "ILoveTheUSA", "iLoveTheUSA", "DBHostCountry", "SetSlot123ToInput456", "ILoveTheUSANetworkInTheUSA", "Limit_IOC_Duration", "_This_is_a_Test_of_Network123_in_12__days_", "ASongAboutTheABCsIsFunToSing", "CFDs", "DBSettings", "IWouldLove1Apple", "Employee22IsCool", "SubIDIn", "ConfigureABCsImmediately", "UseMainNameOnBehalfOfSubNameInOrders" ];
// Take a single camel case string and convert it to a string of separate words (with spaces) at the camel-case boundaries.
//
// E.g.:
// __ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D
// --> To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D
// helloThere --> Hello There
// HelloThere --> Hello There
// ILoveTheUSA --> I Love The USA
// iLoveTheUSA --> I Love The USA
// DBHostCountry --> DB Host Country
// SetSlot123ToInput456 --> Set Slot 123 To Input 456
// ILoveTheUSANetworkInTheUSA --> I Love The USA Network In The USA
// Limit_IOC_Duration --> Limit IOC Duration
// This_is_a_Test_of_Network123_in_12_days --> This Is A Test Of Network 123 In 12 Days
// ASongAboutTheABCsIsFunToSing --> A Song About The ABCs Is Fun To Sing
// CFDs --> CFDs
// DBSettings --> DB Settings
// IWouldLove1Apple --> I Would Love 1 Apple
// Employee22IsCool --> Employee 22 Is Cool
// SubIDIn --> Sub ID In
// ConfigureCFDsImmediately --> Configure CFDs Immediately
// UseTakerLoginForOnBehalfOfSubIDInOrders --> Use Taker Login For On Behalf Of Sub ID In Orders
//
function camelCaseToTitleCase(in_camelCaseString) {
var result = in_camelCaseString // "__ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D"
.replace(/(_)+/g, ' ') // " ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser 456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D"
.replace(/([a-z])([A-Z][a-z])/g, "$1 $2") // " To Get YourGEDIn TimeASong About The26ABCs IsOf The Essence ButAPersonalIDCard For User456In Room26AContainingABC26Times IsNot AsEasy As123ForC3POOrR2D2Or2R2D"
.replace(/([A-Z][a-z])([A-Z])/g, "$1 $2") // " To Get YourGEDIn TimeASong About The26ABCs Is Of The Essence ButAPersonalIDCard For User456In Room26AContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
.replace(/([a-z])([A-Z]+[a-z])/g, "$1 $2") // " To Get Your GEDIn Time ASong About The26ABCs Is Of The Essence But APersonal IDCard For User456In Room26AContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
.replace(/([A-Z]+)([A-Z][a-z][a-z])/g, "$1 $2") // " To Get Your GEDIn Time A Song About The26ABCs Is Of The Essence But A Personal ID Card For User456In Room26A ContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
.replace(/([a-z]+)([A-Z0-9]+)/g, "$1 $2") // " To Get Your GEDIn Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC26Times Is Not As Easy As 123For C3POOr R2D2Or 2R2D"
// Note: the next regex includes a special case to exclude plurals of acronyms, e.g. "ABCs"
.replace(/([A-Z]+)([A-Z][a-rt-z][a-z]*)/g, "$1 $2") // " To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC26Times Is Not As Easy As 123For C3PO Or R2D2Or 2R2D"
.replace(/([0-9])([A-Z][a-z]+)/g, "$1 $2") // " To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC 26Times Is Not As Easy As 123For C3PO Or R2D2Or 2R2D"
// Note: the next two regexes use {2,} instead of + to add space on phrases like Room26A and 26ABCs but not on phrases like R2D2 and C3PO"
.replace(/([A-Z]{2,})([0-9]{2,})/g, "$1 $2") // " To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D"
.replace(/([0-9]{2,})([A-Z]{2,})/g, "$1 $2") // " To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D"
.trim() // "To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D"
;
// capitalize the first letter
return result.charAt(0).toUpperCase() + result.slice(1);
}
for (var i = 0; i < mystrings.length; i++) {
jQuery(document.body).append("<br />\"");
jQuery(document.body).append(camelCaseToTitleCase(mystrings[i]));
jQuery(document.body).append("\"<br>(was: \"");
jQuery(document.body).append(mystrings[i]);
jQuery(document.body).append("\") <br />");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
Based on one of the examples above I came up with this:
const camelToTitle = (camelCase) => camelCase
.replace(/([A-Z])/g, (match) => ` ${match}`)
.replace(/^./, (match) => match.toUpperCase())
.trim()
It works for me because it uses .trim() to handle the edge case where the first letter is capitalized and you end up with a extra leading space.
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
Ok, I'm a few years late to the game, but I had a similar question, and I wanted to make a one-replace solution for every possible input. I must give most of the credit to #ZenMaster in this thread and #Benjamin Udink ten Cate in this thread.
Here's the code:
var camelEdges = /([A-Z](?=[A-Z][a-z])|[^A-Z](?=[A-Z])|[a-zA-Z](?=[^a-zA-Z]))/g;
var textArray = ["lowercase",
"Class",
"MyClass",
"HTML",
"PDFLoader",
"AString",
"SimpleXMLParser",
"GL11Version",
"99Bottles",
"May5",
"BFG9000"];
var text;
var resultArray = [];
for (var i = 0; i < textArray.length; i++){
text = textArray[i];
text = text.replace(camelEdges,'$1 ');
text = text.charAt(0).toUpperCase() + text.slice(1);
resultArray.push(text);
}
It has three clauses, all using lookahead to prevent the regex engine from consuming too many characters:
[A-Z](?=[A-Z][a-z]) looks for a capital letter that is followed by a capital then a lowercase. This is to end acronyms like USA.
[^A-Z](?=[A-Z]) looks for a non-capital-letter followed by a capital letter. This ends words like myWord and symbols like 99Bottles.
[a-zA-Z](?=[^a-zA-Z]) looks for a letter followed by a non-letter. This ends words before symbols like BFG9000.
This question was at the top of my search results, so hopefully I can save others some time!
Here's my version of it. It adds a space before every UpperCase english letter that comes after a lowercase english letter and also capitalizes the first letter if needed:
For example:
thisIsCamelCase --> This Is Camel Case
this IsCamelCase --> This Is Camel Case
thisIsCamelCase123 --> This Is Camel Case123
function camelCaseToTitleCase(camelCase){
if (camelCase == null || camelCase == "") {
return camelCase;
}
camelCase = camelCase.trim();
var newText = "";
for (var i = 0; i < camelCase.length; i++) {
if (/[A-Z]/.test(camelCase[i])
&& i != 0
&& /[a-z]/.test(camelCase[i-1])) {
newText += " ";
}
if (i == 0 && /[a-z]/.test(camelCase[i]))
{
newText += camelCase[i].toUpperCase();
} else {
newText += camelCase[i];
}
}
return newText;
}
This implementation takes consecutive uppercase letters and numbers in consideration.
function camelToTitleCase(str) {
return str
.replace(/[0-9]{2,}/g, match => ` ${match} `)
.replace(/[^A-Z0-9][A-Z]/g, match => `${match[0]} ${match[1]}`)
.replace(/[A-Z][A-Z][^A-Z0-9]/g, match => `${match[0]} ${match[1]}${match[2]}`)
.replace(/[ ]{2,}/g, match => ' ')
.replace(/\s./g, match => match.toUpperCase())
.replace(/^./, match => match.toUpperCase())
.trim();
}
// ----------------------------------------------------- //
var testSet = [
'camelCase',
'camelTOPCase',
'aP2PConnection',
'superSimpleExample',
'aGoodIPAddress',
'goodNumber90text',
'bad132Number90text',
];
testSet.forEach(function(item) {
console.log(item, '->', camelToTitleCase(item));
});
Expected output:
camelCase -> Camel Case
camelTOPCase -> Camel TOP Case
aP2PConnection -> A P2P Connection
superSimpleExample -> Super Simple Example
aGoodIPAddress -> A Good IP Address
goodNumber90text -> Good Number 90 Text
bad132Number90text -> Bad 132 Number 90 Text
You can use a function like this:
function fixStr(str) {
var out = str.replace(/^\s*/, ""); // strip leading spaces
out = out.replace(/^[a-z]|[^\s][A-Z]/g, function(str, offset) {
if (offset == 0) {
return(str.toUpperCase());
} else {
return(str.substr(0,1) + " " + str.substr(1).toUpperCase());
}
});
return(out);
}
"hello World" ==> "Hello World"
"HelloWorld" ==> "Hello World"
"FunInTheSun" ==? "Fun In The Sun"
Code with a bunch of test strings here: http://jsfiddle.net/jfriend00/FWLuV/.
Alternate version that keeps leading spaces here: http://jsfiddle.net/jfriend00/Uy2ac/.
One more solution based on RegEx.
respace(str) {
const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g;
return str.replace(regex, '$& ');
}
Explanation
The above RegEx consist of two similar parts separated by OR operator. The first half:
([A-Z]) - matches uppercase letters...
(?=[A-Z][a-z]) - followed by a sequence of uppercase and lowercase letters.
When applied to sequence FOo, this effectively matches its F letter.
Or the second scenario:
([a-z]) - matches lowercase letters...
(?=[A-Z]) - followed by an uppercase letter.
When applied to sequence barFoo, this effectively matches its r letter.
When all replace candidates were found, the last thing to do is to replace them with the same letter but with an additional space character. For this we can use '$& ' as a replacement, and it will resolve to a matched substring followed by a space character.
Example
const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g
const testWords = ['ACoolExample', 'fooBar', 'INAndOUT', 'QWERTY', 'fooBBar']
testWords.map(w => w.replace(regex, '$& '))
->(5) ["A Cool Example", "foo Bar", "IN And OUT", "QWERTY", "foo B Bar"]
If you deal with Capital Camel Case this snippet can help you, also it contains some specs so you could be sure that it matches appropriate to your case.
export const fromCamelCaseToSentence = (word) =>
word
.replace(/([A-Z][a-z]+)/g, ' $1')
.replace(/([A-Z]{2,})/g, ' $1')
.replace(/\s{2,}/g, ' ')
.trim();
And specs:
describe('fromCamelCaseToSentence', () => {
test('does not fall with a single word', () => {
expect(fromCamelCaseToSentence('Approved')).toContain('Approved')
expect(fromCamelCaseToSentence('MDA')).toContain('MDA')
})
test('does not fall with an empty string', () => {
expect(fromCamelCaseToSentence('')).toContain('')
})
test('returns the separated by space words', () => {
expect(fromCamelCaseToSentence('NotApprovedStatus')).toContain('Not Approved Status')
expect(fromCamelCaseToSentence('GDBState')).toContain('GDB State')
expect(fromCamelCaseToSentence('StatusDGG')).toContain('Status DGG')
})
})
My split case solution which behaves the way I want:
const splitCase = s => !s || s.indexOf(' ') >= 0 ? s :
(s.charAt(0).toUpperCase() + s.substring(1))
.split(/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/g)
.map(x => x.replace(/([0-9]+)/g,'$1 '))
.join(' ')
Input
'a,abc,TheId,TheID,TheIDWord,TheID2Word,Leave me Alone!'
.split(',').map(splitCase)
.forEach(x => console.log(x))
Output
A
Abc
The Id
The ID
The ID Word
The ID2 Word
Leave me Alone!
As this above function requires Lookbehind in JS which isn't currently implemented in Safari, I've rewritten the implementation to not use RegEx below:
const isUpper = c => c >= 'A' && c <= 'Z'
const isDigit = c => c >= '0' && c <= '9'
const upperOrDigit = c => isUpper(c) || isDigit(c)
function splitCase(s) {
let to = []
if (typeof s != 'string') return to
let lastSplit = 0
for (let i=0; i<s.length; i++) {
let c = s[i]
let prev = i>0 ? s[i-1] : null
let next = i+1 < s.length ? s[i+1] : null
if (upperOrDigit(c) && (!upperOrDigit(prev) || !upperOrDigit(next))) {
to.push(s.substring(lastSplit, i))
lastSplit = i
}
}
to.push(s.substring(lastSplit, s.length))
return to.filter(x => !!x)
}
try this library
http://sugarjs.com/api/String/titleize
'man from the boondocks'.titleize()>"Man from the Boondocks"
'x-men: the last stand'.titleize()>"X Men: The Last Stand"
'TheManWithoutAPast'.titleize()>"The Man Without a Past"
'raiders_of_the_lost_ark'.titleize()>"Raiders of the Lost Ark"
Using JS's String.prototype.replace() and String.prototype.toUpperCase()
const str = "thisIsATestString";
const res = str.replace(/^[a-z]|[A-Z]/g, (c, i) => (i? " " : "") + c.toUpperCase());
console.log(res); // "This Is A Test String"
The most compatible answer for consecutive capital-case words is this:
const text = 'theKD';
const result = text.replace(/([A-Z]{1,})/g, " $1");
const finalResult = result.charAt(0).toUpperCase() + result.slice(1);
console.log(finalResult);
It's also compatible with The KD and it will not convert it to The K D.
None of the answers above worked perfectly for me, so had to come with own bicycle:
function camelCaseToTitle(camelCase) {
if (!camelCase) {
return '';
}
var pascalCase = camelCase.charAt(0).toUpperCase() + camelCase.substr(1);
return pascalCase
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
.replace(/([a-z])([0-9])/gi, '$1 $2')
.replace(/([0-9])([a-z])/gi, '$1 $2');
}
Test cases:
null => ''
'' => ''
'simpleString' => 'Simple String'
'stringWithABBREVIATIONInside => 'String With ABBREVIATION Inside'
'stringWithNumber123' => 'String With Number 123'
'complexExampleWith123ABBR890Etc' => 'Complex Example With 123 ABBR 890 Etc'
This works for me check this out
CamelcaseToWord("MyName"); // returns My Name
function CamelcaseToWord(string){
return string.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1");
}
I didn't try everyone's answer, but the few solutions I tinkered with did not match all of my requirements.
I was able to come up with something that did...
export const jsObjToCSSString = (o={}) =>
Object.keys(o)
.map(key => ({ key, value: o[key] }))
.map(({key, value}) =>
({
key: key.replace( /([A-Z])/g, "-$1").toLowerCase(),
value
})
)
.reduce(
(css, {key, value}) =>
`${css} ${key}: ${value}; `.trim(),
'')
I think this can be done just with the reg exp /([a-z]|[A-Z]+)([A-Z])/g and replacement "$1 $2".
ILoveTheUSADope -> I Love The USA Dope
Below is link which demonstrates camel case string to sentence string using regex.
Input
myCamelCaseSTRINGToSPLITDemo
Output
my Camel Case STRING To SPLIT Demo
This is regex for conversion of camel case to sentence text
(?=[A-Z][a-z])|([A-Z]+)([A-Z][a-rt-z][a-z]\*)
with $1 $2 as subsitution.
Click to view the conversion on regex
Input
javaScript
Output
Java Script
var text = 'javaScript';
text.replace(/([a-z])([A-Z][a-z])/g, "$1 $2").charAt(0).toUpperCase()+text.slice(1).replace(/([a-z])([A-Z][a-z])/g, "$1 $2");
HTTPRequest_ToServer-AndWaiting --> HTTP Request To Server And Waiting
function toSpaceCase(str) {
return str
.replace(/[-_]/g, ' ')
/*
* insert a space between lower & upper
* HttpRequest => Http Request
*/
.replace(/([a-z])([A-Z])/g, '$1 $2')
/*
* space before last upper in a sequence followed by lower
* XMLHttp => XML Http
*/
.replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
// uppercase the first character
.replace(/^./, str => str.toUpperCase())
.replace(/\s+/g, ' ')
.trim();
}
const input = 'HTTPRequest_ToServer-AndWaiting';
const result = toSpaceCase(input);
console.log(input,'-->', result)
Undercover C programmer. If like me you want to preserve acronyms and don't want to look at cryptic patterns, then perhaps you may like this:
function isUpperCase (str) {
return str === str.toUpperCase()
}
export function camelCaseToTitle (str) {
for (let i = str.length - 1; i > 0; i--) {
if (!isUpperCase(str[i - 1]) && isUpperCase(str[i])) {
str = str.slice(0, i) + ' ' + str.slice(i)
}
}
return str.charAt(0).toUpperCase() + str.slice(1)
}
This solution works also for other Unicode characters which are not in the [A-Z] range. E.g. Ä, Ö, Å.
let camelCaseToTitleCase = (s) => (
s.split("").reduce(
(acc, letter, i) => (
i === 0 || console.log(acc, letter, i)
? [...acc, letter.toUpperCase()]
: letter === letter.toUpperCase()
? [...acc, " ", letter]
: [...acc, letter]
), []
).join("")
)
const myString = "ArchipelagoOfÅland"
camelCaseToTitleCase(myString)
Adding yet another ES6 solution that I liked better after not being happy with a few thoughts above.
https://codepen.io/902Labs/pen/mxdxRv?editors=0010#0
const camelize = (str) => str
.split(' ')
.map(([first, ...theRest]) => (
`${first.toUpperCase()}${theRest.join('').toLowerCase()}`)
)
.join(' ');

Categories

Resources