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!
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
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 (ie /\\.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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.