Reputation: 473
I try to transform string using String replace method and regular expression. How can I remove underscores in a given string?
let string = 'court_order_state'
string = string.replace(/_([a-z])/g, (_, match) => match.toUpperCase())
console.log(string)
Expected result:
COURT ORDER STATE
Upvotes: 2
Views: 2259
Reputation: 163352
In your code you could match either and underscore or the start of the string (?:_|^)
to also match the first word and match 1+ times a-z using a quantifier [a-z]+
Then append a space after each call toUpperCase.
let string = 'court_order_state';
string = string.replace(/(?:_|^)([a-z]+)/g, (m, g1) => g1.toUpperCase() + " ");
console.log(string)
Upvotes: 1
Reputation: 106
Instead of matching the first character just after every _ and making them uppercase (from the regex that you have used), you can simply convert the entire string to uppercase, and replace the _ with space by the following:
let string = 'court_order_state';
string = string.toUpperCase().replace(/_+/g, " ");
console.log(string);
Upvotes: 0
Reputation: 1884
It can be as simple as the below:
let string = 'court_order_state'
string = string.replace(/_/g, ' ').toUpperCase();
console.log(string);
Here the 'g' represents global, whereas the '/' is surrounded by what we're looking for.
Upvotes: 0
Reputation: 11096
let string = 'court_order_____state'
string = string.replace(/_+/g, ' ').toUpperCase()
console.log(string)
Upvotes: 0
Reputation: 5201
You could use JavaScript replace
function, passing as input:
/_/g
as searchvalue
parameter (the g
modifier is used to perform a global match, i.e. find all matches rather than stopping after the first one);
(blank space) as newvalue
parameter.let string = 'court_order_state'
string = string.replace(/_/g, ' ').toUpperCase();
console.log(string);
Upvotes: 3