0

Appreciate any help to write a nodejs regex.

First search for the exact words "ChildBucketOne" and "ChildBucketTwo" and add exact word ParentBucket before every occurence of ChildBucketOne or/and ChildBucketTwo.

I am trying to use one regex.

Input1: webApplication.ChildBucketOne Input2: webApplication.ChildBucketTwo

Output: webApplication.ParentBucket.ChildBucket.ChildBucketOne

webApplication.ParentBucket.ChildBucket.ChildBucketTwo

Thanks!

Eva
  • 109
  • 9
  • The posted question does not appear to include [any attempt](https://idownvotedbecau.se/noattempt/) at all to solve the problem. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific roadblock you're running into in a [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Jun 16 '19 at 05:47

2 Answers2

1

You can simply use String replace function of JavaScript

let input1 = 'webApplication.ChildBucketOne';
let input2 = 'webApplication.ChildBucketTwo';


function preprocess(input){

 return input.replace('.ChildBucket', '.ParentBucket.ChildBucket.ChildBucket');

}


console.log(preprocess(input1));
console.log(preprocess(input2));

Live in action - https://jsitor.com/IUb7cRtvf

Ashvin777
  • 1,446
  • 13
  • 19
1

Node.js is basically the same as Javascript, except that it runs on the server.

Back to your question, below is the snippet to find all occurrence of .ChildBucket, and replace them by .ParentBucket.ChildBucket.

const original = `
# dummy text 1
webApplication.ChildBucketOne
# dummy text 2
webApplication.ChildBucketTwo
# dummy text 3
`

console.log('--- Original ---')
console.log(original)

const replaced = original.replace(/\.ChildBucket/g, '.ParentBucket.ChildBucket')

console.log('--- Replaced ---')
console.log(replaced)

Explanation

You see that I use regular expression (i.e. /\.ChildBucket/g) instead of a string because the replace function will only replace the first occurrence of the matching string by default. Using regular expression with the g modifier will turn it into the global match, which replaces all the occurrence.

Output

--- Original ---
# dummy text 1
webApplication.ChildBucketOne
# dummy text 2
webApplication.ChildBucketTwo
# dummy text 3
--- Replaced ---
# dummy text 1
webApplication.ParentBucket.ChildBucketOne
# dummy text 2
webApplication.ParentBucket.ChildBucketTwo
# dummy text 3
Tim Wong
  • 600
  • 3
  • 9