I am trying to replace a string starting with a specific symbol '@' with the symbol '%', but the condition is that the symbol should be at the start of the string.
For eg.
@@@hello@hi@@
should be replaced by
%%%hello@hi@@
I have come up with the regex that matches the starting '@' symbols, but I am able to replace it only once, instead of replacing it with the number of times it matched.
The code is
var str = "@@@hello@hi@@";
var exp = new RegExp('^@+', 'g');
var mystr = str.replace(exp, '%');
But, it outputs
%hello@hi@@
But, the intended output is
%%%hello@hi@@
My current solution is something like this:
var str = "@@@hello@hi@@";
var match = str.match(/^@+/g)[0];
var new_str = str.replace(match, "");
var diff_count = str.length-new_str.length;
var new_sub_str = Array(diff_count+1).join("%")
var mystr = new_sub_str + new_str;
This solution does give me the intended output, but I am worried about the performance.
Is there any better way to achieve this ?
You can use a callback function:
var mystr = '@@@hello@hi@@'.replace(/^@+/g, function(match) {
return Array(match.length + 1).join('%');
});
document.write(mystr);
The Array(n).join(s)
construction is simply a shorthand way of repeating the string s
n-1
times.
An interesting solution without regexp:
var mystr = '@@@@@hello@hi@@'.split('').map(function(item) {
if (item == '@' && !this.stop) {
return '%';
} else {
this.stop = true;
return item;
}
}, {}).join('');
console.log(mystr);
And an alternative:
var mystr = Array.prototype.map.call('@@@@@hello@hi@@', function(item) {
if (item == '@' && !this.stop) {
return '%';
} else {
this.stop = true;
return item;
}
}, {}).join('');
console.log(mystr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With