Reputation: 275
As the question says, I'm trying to match one occurrence of a character and at the same time 2 occurrences of another. For example, in the string "_Hell_o"
I would like to match the first "_"
there and in the case of "++Hello"
I would like to match exactly both "+"
. Basically a function like this:
function change(str){
console.log(str.replace(/[_+{2}]/, ''));
change("++Hello");
change("_Hello");
change("+Hello");
And the outputs to be
>>> Hello
>>> Hello
>>> +Hello
But that function does not work
Upvotes: 1
Views: 398
Reputation: 403218
/^_{1}|\+{2}/g
does the trick.
function change(str){
console.log(str.replace(/^_{1}|\+{2}/g, ''));
}
change("++Hello");
change("+++Hello");
change("_Hell__o");
change("___Hello");
change("+Hello");
Upvotes: 4
Reputation: 3444
str.replace('++', '').replace('_', '')
Simplified version of the answer by YCF_L. Like YCF_L's answer, it will remove the first occurrence of ++
(if any) and the first occurrence of _
(if any).
Upvotes: 0
Reputation: 60046
You can solve your problem using two replace for example :
var array = ["++Hello", "_Hello", "+Hello"];
for (var i = 0; i < array.length; i++) {
console.log(array[i].replace(/\+{2}/, '').replace(/_(.*)/, '$1'))
}
Upvotes: 3