Shuail_CR007
Shuail_CR007

Reputation: 312

Split String and move to newline in JavaScript

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

Upvotes: 0

Views: 45

Answers (1)

Himanshu Pandey
Himanshu Pandey

Reputation: 708

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)

Upvotes: 1

Related Questions