Home > Back-end >  How split string into separate variables based on several characters in Java Script
How split string into separate variables based on several characters in Java Script

Time:11-04

There is a String variable that comes value like the following.

"COMPANY=10^INVOICE_ID=100021^"

I need to get this into two variables like Company and InvoieId.

What will be possible ways to do that JS?

CodePudding user response:

let st = "COMPANY=10^INVOICE_ID=100021^"
let company = st.split("COMPANY=")[1].split("^")[0]
let invoice = st.split("INVOICE_ID=")[1].split("^")[0]

CodePudding user response:

Here is a dynamic way. You can grab any value from obj.

const str = "COMPANY=10^INVOICE_ID=100021^"

const obj = {}
const strArr = str.split('^')

strArr.forEach(str => {
    const [key, value] = str.split('=')
    obj[key] = value
})

const {COMPANY, INVOICE_ID } = obj

console.log(INVOICE_ID, COMPANY)

CodePudding user response:

We can also do it via regular expression

Regex101 demo

let str = `COMPANY=10^INVOICE_ID=100021^`
let regex = /(\w )=\d /g
let match = regex.exec(str)
while(match){
  console.log(match[1])
  match = regex.exec(str)
}

  • Related