2

I have an input string like this:

ABCDEFG[HIJKLMN]OPQRSTUVWXYZ

How can I replace each character in the string between the [] with an X (resulting in the same number of Xs as there were characters)?

For example, with the input above, I would like an output of:

ABCDEFG[XXXXXXX]OPQRSTUVWXYZ

I am using JavaScript's RegEx for this and would prefer if answers could be an implementation that does this using JavaScript's RegEx Replace function.


I am new to RegEx so please explain what you do and (if possible) link articles to where I can get further help.

2
  • 1
    With the latest ECMAScript 2018, you may do that easily. If you need to target other environments, it is also easy, but requires a bit of code. Commented Aug 27, 2018 at 22:59
  • 1
    I will run in javascript,can you tell the code? Commented Aug 27, 2018 at 23:01

4 Answers 4

2

Using replace() and passing the match to a function as parameter, and then Array(m.length).join("X") to generate the X's needed:

var str = "ABCDEFG[HIJKLMN]OPQRSTUVWXYZ"

str = str.replace(/\[[A-Z]*\]/g,(m)=>"["+Array(m.length-1).join("X")+"]")

console.log(str);

We could use also .* instead of [A-Z] in the regex to match any character.

About regular expressions there are thousands of resources, specifically in JavaScript, you could see Regular Expressions MDN but the best way to learn, in my opinion, is practicing, I find regex101 useful.

Sign up to request clarification or add additional context in comments.

Comments

0

const str="ABCDEFG[HIJKLMN]OPQRSTUVWXYZ";
const run=str=>str.replace(/\[.*]/,(a,b,c)=>c=a.replace(/[^\[\]]/g,x=>x="X"));
console.log(run(str));

The first pattern /\[.*]/ is to select letters inside bracket [] and the second pattern /[^\[\]]/ is to replace the letters to "X"

Comments

0

We can observe that every individual letter you wish to match is followed by a series of zero or more non-'[' characters, until a ']' is found. This is quite simple to express in JavaScript-friendly regex:

/[A-Z](?=[^\[]*\])/g

regex101 example

(?= ) is a "positive lookahead assertion"; it peeks ahead of the current matching point, without consuming characters, to verify its contents are matched. In this case, "[^[]*]" matches exactly what I described above.

Now you can substitute each [A-Z] matched with a single 'X'.

Comments

0

You can use the following solution to replace a string between two square brackets:

const rxp = /\[.*?\]/g;
"ABCDEFG[HIJKLMN]OPQRSTUVWXYZ".replace(rxp, (x) => {
    return x.replace(rxp, "X".repeat(x.length)-2);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.