Rayms
Rayms

Reputation: 23

Replace all letters which is not between square bracket in Javascript

I need to replace all letter by "a" in string which is not between square brackets in javascript.

let value = "foo[bar9]12a"; 
// should be replaced by "aaa[bar9]12a"

let value = "[foo]bar5[foo]"; 
// should be replaced by "[foo]aaa5[foo]"

I tried with regex but it doesn't work like expected:

const value = "foo[bar9]12a";
const alphaRegex = /(?:[\d*]|\[.*\])|(([a-zA-Z]))/gmi;
const result = value.replace(alphaRegex, 'a');

// result = "aaaaaa";

Any suggestions ?

Upvotes: 1

Views: 162

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370979

One option is to match a non-bracket character, then lookahead for non-bracket characters eventually followed by a [ or the end of the string:

const value = "foo[bar9]12a";
console.log(
  value.replace(/[^[\]](?=[^[\]]*(?:\[|$))/g, 'a')
);

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627087

You may use

const value = "foo[bar9]12a";
const rx = /(\[[^\][]*])|[a-z]/gi;
const result = value.replace(rx, function($0, $1) { return $1 || 'a'; });
console.log(result);

The /(\[[^\][]*])|[a-z]/gi regex matches all occurrences (in a case insensitive way) of

  • (\[[^\][]*]) - Capturing group 1: [, 0+ chars other than [ and ] and then a ]
  • | - or
  • [a-z] - an ASCII letter.

If Group 1 matched, the return value is the captured substring, else, a.

Upvotes: 5

Related Questions