-1

I need to replace a text inside a string.

eg: The text will be

Hello! This is a test [query] which i am using for [transformation]

And what i need is to extract the string's inside [] with another string mapping object i have. which is in the form

{
"query":'ab',
"transformation":'cd'
}

So the result string will be Hello! This is a test [ab] which i am using for [cd]

Sagar Acharya
  • 1,763
  • 2
  • 19
  • 38

2 Answers2

0

var input = "Hello! This is a test [query] which i am using for [transformation]"

const query = {
"query":'ab',
"transformation":'cd'
}

Object.keys(query).forEach(key => {
  input = input.replace(key, query[key])
})

console.log(input)
wangdev87
  • 8,611
  • 3
  • 8
  • 31
0

const str =
  'Hello! This is a test [query] which i am using for [transformation]';

const mapping = {
  query: 'ab',
  transformation: 'cd'
};

const res = Object.keys(mapping).reduce(
  (modified, key) => modified.replace(key, mapping[key]),
  str
);

console.log(res);
michael
  • 4,053
  • 2
  • 12
  • 31