0

I have a sample string in which I need to move to a new line if the value is present in the array using Javascript.

var str="name:stain empid:145 age:53   Dob:29/07/1993 sex:m"
var arr=['name','age','Dob'];

Required output:

name:stain empid:145
age:53   
Dob:29/07/1993 sex:m

2
  • 2
    str.replace(new RegExp(`\\b(${arr.join("|")})\\b`, "g"), "\n$1") Commented Jun 3, 2020 at 14:51
  • thanks @CRice ... it worked Commented Jun 3, 2020 at 15:03

1 Answer 1

1

As @CRice mention good use of regex. $1 is the first group from your regular expression MDN RegExp

var str="name:stain empid:145 age:53   Dob:29/07/1993 sex:m"
var arr=['name','age','Dob'];
const result = str.replace(new RegExp(`\\b(${arr.join("|")})\\b`, "g"), "\n$1")
console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.