Home > Blockchain >  javascript split with line or space
javascript split with line or space

Time:06-24

I'm trying to split this code

<h1>
                                   999 street
                                   <br>
                                   city
                                   , 
                                   AA
                                   
                                   90777
                                   <br>
      </h1>

So far I can get this:

const address = document.querySelector('h1')

let street = address.split(',')
let pre_postalCode = street[2]

So I can get the part after , But the following code doesn't work

let pre_postalCode2 = pre_postalCode.split(' ')
let postalCode = pre_postalCode2[1]

I can't get the "90777", it returns nothing I tried something like

let pre_postalCode2 = pre_postalCode.replace(/\br/g, " ").split(" ")

It doesn't work

CodePudding user response:

With this regex, you can split the text by newline value. After this, you must have a pattern or you must know the order of the specific word/line that you want to get the value from. For example, if you know that the postal code will always be on the 8th line then you can do this.

const data = `<h1>
                                   999 street
                                   <br>
                                   city
                                   , 
                                   AA
                                   
                                   90777
                                   <br>
      </h1>`;
let values = data.split(/\r?\n/).map(n => n.trim());
console.log(values[7]);

CodePudding user response:

I hope this helps.

var arr = `<h1>
                                   999 street
                                   <br>
                                   city
                                   , 
                                   AA
                                   
                                   90777
                                   <br>
      </h1>`.split("\n").map(val => val.trim()).filter(val =>  val && val !== "<br>" && val !== ",");
console.log(arr);

CodePudding user response:

You can identify just numbers from some parts of the string and work with them:

const str = `<h1>
                                   999 street
                                   <br>
                                   city
                                   , 
                                   AA
                                   
                                   90777
                                   <br>
      </h1>`

matches = str.split(',')[1].match(/\d /g);

matches.forEach(res => console.log(res));

  • Related