Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace characters using Regex positive/negative lookahead?

I have this string :

var a='abc123#xyz123';

I want to build 2 regexes replace functions which :

1) Replace all characters that do have a future '#' - with '*' (not including '#')

so the result should look like :

'******#xyz123'

2) Replace all characters that do not have a future '#' - with '*' (not including '#')

so the result should look like :

'abc123#******'

What have I tried :

For the positive lookahead :

var a='abc123#xyz123';
alert(a.replace(/(.+(?=#))+/ig,'*'));  //*#xyz123 --wrong result since it is greedy...

Question :

How can I make my regexes work as expected ?

like image 693
Royi Namir Avatar asked Mar 21 '23 20:03

Royi Namir


2 Answers

First part using lookahead:

repl = a.replace(/.(?=[^#]*#)/g, "*");
//=> "******#xyz123"

Explanation:

This regex finds any character that is followed by # using lookahead and replaced that with *.

Second part using replace callback:

repla = a.replace(/#(.*)$/, function(m, t) { return m[0] + t.replace(/./g, '*'); } );
//=> abc123#******

Explanation:

This code finds text after #. Inside the callback function is replaces every character with asterisk.

like image 191
anubhava Avatar answered Apr 26 '23 01:04

anubhava


You can use indexOf and substr for this instead:

function maskBeforeAfter(before, str, character, maskCharacter) {
    character = character || '#';
    maskCharacter = maskCharacter || '*';

    var characterPosition = str.indexOf(character);
    if (characterPosition > -1) {
        var mask = '';
        if (before) {
            for (var i = 0; i < characterPosition; i++) {
                mask += maskCharacter;
            }
            return mask + str.substr(characterPosition);
        } else {
            for (var i = 0; i < str.length - characterPosition - 1; i++) {
                mask += maskCharacter;
            }
            return str.substr(0, characterPosition + 1) + mask;
        }
    }
    return str;
}

function maskBefore(str, character, maskCharacter) {
    return maskBeforeAfter(true, str, character, maskCharacter);
}

function maskAfter(str, character, maskCharacter) {
    return maskBeforeAfter(false, str, character, maskCharacter);
}

> var a = 'abc12345#xyz123';

> maskBefore(a);
"********#xyz123"

> maskAfter(a);
"abc12345#******"
like image 44
h2ooooooo Avatar answered Apr 26 '23 01:04

h2ooooooo