yxu296
yxu296

Reputation: 399

regex to match first half of any string?

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

Answers (3)

RomanPerekhrest
RomanPerekhrest

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

SteepZero
SteepZero

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

Zoe Edwards
Zoe Edwards

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

Related Questions