Reputation: 399
I find this hard to do without variable quantifiers
I'd like to be able to do something like
var halfStrLength = string.length /2
string = string.replace(/.(?=.{halfStrLength})/g, '*')
// replaces all but the last half of string with *
Upvotes: 0
Views: 1132
Reputation: 92854
replaces all but the last half of string with
*
Simply with String.substr()
and String.padStart()
(Ecmascript 6) functions:
var s = 'halfStrLength',
half = s.substr(s.length / 2).padStart(s.length, '*');
console.log(half);
Upvotes: 0
Reputation: 364
You may create new RegExp like this:
var times = string.length / 2;
var regexp = new RegExp('(.{'+times+'})');
string = string.replace(regexp,'*');
Upvotes: 1
Reputation: 13677
Consider using str.slice(beginIndex[, endIndex])
instead. It returns a new string.
You might want to round the halfStrLength down or up, as you don’t want to try and split a string in half by a decimal.
Upvotes: 2