简体   繁体   中英

Javascript - Convert string title-case with hyphen in title

I am attempting to convert any string that I have into a title case format. I am able to accomplish this for titles without any hyphens. When a hyphen is introduced I am getting a s.match(...) is null error. I've attempted to adjust the code below but I have been unsuccessful. How can I adjust the function below in order to handle not only regular strings but when a hyphen is introduced.

I have 2 examples in my code snippet. First firstTitle , is a basic string that is converted the way I am expecting it to. Second, secondTitle is an example when a hyphen is introduced and is erroring.

My expected outcome is for secondTitle to return back as : Retail Sales - Online Order

 let firstTitle = "Testing string to title case" let firstCase = firstTitle .toLowerCase().split(' ').map(function (s) { let letterToCapitalize = s.match(/\\w/)[0]; return s.replace(letterToCapitalize, letterToCapitalize.toUpperCase()) }).join(' '); console.log(firstCase ) let secondTitle= "Retail sales - online order" let secondCase= secondTitle.toLowerCase().split(' ').map(function (s) { let letterToCapitalize = s.match(/\\w/)[0]; return s.replace(letterToCapitalize, letterToCapitalize.toUpperCase()) }).join(' '); console.log(secondCase)

 let secondTitle = "Retail sales - online order"; let secondCase = secondTitle.toLowerCase().replace(/\\b[az]/g, function (s) { return s.toUpperCase(); }); console.log(secondCase);

Rather than splitting the string, you can replace all the lowercase characters. If you use the boundary anchor followed by the alpha set, you can match the first character of the string and any character preceeded by whitespace. Then all you have to do is uppercase it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM