Add Capitalized Letter After Each Dash In A String
Here is an example of what my problem is let str = 'A-bb-cc-dd' How do I make it so that the string will return 'A-Bb-Cc-Dd'
Solution 1:
You can use a simple regex in a replace statement:
let str = 'A-bb-cc-dd'console.log(
str.replace(/\-[a-z]/g, match => match.toUpperCase())
)
\-[a-z]
will simply match a lowercase character after a dash, match.toUpperCase()
makes all letters in the string uppercase.
Solution 2:
You can do it like this,
let str = 'A-bb-cc-dd';
let result = (str.split('-').map(e=>e.charAt(0).toUpperCase() + e.slice(1))).join('-');
console.log(result);
Solution 3:
You can split
by the string by -
delimiter then use map to create a new array where the first character will be uppercased
using toUpperCase
and then use join
to recreate the string
let k = 'A-bb-cc-dd';
let convertedStr = k.split('-').map((item) => {
return item.charAt(0).toUpperCase() + item.slice(1);
}).join('-');
console.log(convertedStr)
How do i make it so that the string will return 'A-Bb-Cc-Dd'
Solution 4:
You can use a JS regular expression and String.replace
like so
const result = 'A-bb-cc-dd'.replace(/(^\w|-\w)/g, c => c.toUpperCase());
console.log(result);
Solution 5:
Use string split, map and join:
let str = 'A-bb-cc-dd';
var array = str.split("-"); //console.log(array);var result = array.map(current => {
return current[0].toUpperCase() + current.substr(1);
});
var end = result.join("-");
console.log(end);
Post a Comment for "Add Capitalized Letter After Each Dash In A String"