user579757
user579757

Reputation: 21

How to change given string to regex modified string using javascript

Example strings :

 2222 
 333333 
 12345 
 111
 123456789
 12345678

Expected result:

2@222
333@333
12@345
111
 123@456@789
 12@345@678

i.e. '@' should be inserted at the 4th,8th,12th etc last position from the end of the string.

I believe this can be done using replace and some other methods in JavaScript.

for validation of output string i have made the regex :

^(\d{1,3})(\.\d{3})*?$

Upvotes: 0

Views: 108

Answers (3)

The fourth bird
The fourth bird

Reputation: 163287

You could match all the digits. In the replacement insert an @ after every third digit from the right using a positive lookahead.

(?=(?:\B\d{3})+$)
  • (?= Positive lookahead, what is on the right is
    • (?:\B\d{3})+ Repeat 1+ times not a word boundary and 3 digits
  • $ Assert end of string
  • ) Close lookahead

Regex demo

const regex = /^\d+$/;
["2222",
  "333333",
  "12345",
  "111",
  "123456789",
  "12345678"
].forEach(s => console.log(
  s.replace(/(?=(?:\B\d{3})+$)/g, "@")
));

Upvotes: 1

Toto
Toto

Reputation: 91385

var test = [
    '111',
    '2222',
    '333333',
    '12345',
    '123456789',
    '1234567890123456'
];
console.log(test.map(function (a) {
  return a.replace(/(?=(?:\B\d{3})+$)/g, '@');
}));

Upvotes: 1

Nick Parsons
Nick Parsons

Reputation: 50684

You can use this regular expression:

/(\d)(\d{3})$/

this will match and group the first digit \d and group the last three \d{3} which are then grouped in their own group. Using the matched groups, you can then reference them in your replacement string using $1 and $2.

See example below:

const transform = str => str.replace(/(\d)(\d{3})$/, '$1@$2');

console.log(transform("2222")); // 2@222
console.log(transform("333333")); // 333@333
console.log(transform("12345")); // 12@345
console.log(transform("111")); // 111

For larger strings of size N, you could use other methods such as .match() and reverse the string like so:

const reverse = str => Array.from(str).reverse().join('');
const transform = str => {
  return reverse(reverse(str).match(/(\d{1,3})/g).join('@'));
}

console.log(transform("2222")); // 2@222
console.log(transform("333333")); // 333@333
console.log(transform("12345")); // 12@345
console.log(transform("111")); // 111
console.log(transform("123456789")); // 123@456@789
console.log(transform("12345678")); // 12@345@678

Upvotes: 1

Related Questions