0

I am trying to write some code that takes a uuid string and returns only the characters between the 2nd and 3rd _ characters in an array. What I currently have below is returning every character in the string in to the array. I have been looking at this for some time and am obviously missing something glaringly obvious I suppose. Can someone maybe point out what is wrong here?

var uuid = "159as_ss_5be0lk875iou_.1345.332.11.2"
var count = 0
var  values = []
            
for(y=0; y<uuid.length; y++){
    if(uuid.charAt(y) == '_'){
        count++
    }
    if(count = 2){
        values.push(uuid.charAt(y))
    }
}
return values

EDIT:

So for my case I would want the values array to contain all of the characters in 5be0lk875iou

  • 4
    why not just split by '_'? and then get the value like this: resultAfterSplit[2] – Rusu Dinu Aug 11 '22 at 11:56
  • 1
    Does this answer your question? [Get Substring between two characters using javascript](https://stackoverflow.com/questions/14867835/get-substring-between-two-characters-using-javascript) – Heretic Monkey Aug 11 '22 at 11:59
  • You can use `uuid.split('_')[2]` – kennarddh Aug 11 '22 at 11:59
  • @RusuDinu for whatever reason that never crossed my mind. Very much easier. Thank you! – user19353552 Aug 11 '22 at 11:59
  • Or https://stackoverflow.com/questions/7365575/how-to-get-text-between-two-characters – Heretic Monkey Aug 11 '22 at 12:00
  • Or [parse a string in javascript by a common delimiter](https://stackoverflow.com/q/17205190/215552) – Heretic Monkey Aug 11 '22 at 12:01
  • As an optimization you could pass a limit to [`strip()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) so that it doesn't have to process the string passed the point of interest. `uuid.split("_", 3)[2]` – 3limin4t0r Aug 11 '22 at 12:05
  • If the string has a fixed length and structure you could also use `uuid.slice(9, 21)`. – 3limin4t0r Aug 11 '22 at 12:13

3 Answers3

0

You can use the split function to do that:

let values = uuid.split("_");
PiFanatic
  • 233
  • 1
  • 4
  • 14
0

You can get the same behavior in less lines of code, like this:

let uuid = "159as_ss_5be0lk875iou_.1345.332.11.2"
let values = uuid.split("_")[2];
Rusu Dinu
  • 477
  • 2
  • 5
  • 16
-1

By using the split function, you can get separate the whole string into smaller parts:

const parts = uuid.split("_");

This will return the following array:

["159as", "ss", "5be0lk875iou", ".1345.332.11.2"]

From here, you can take the string at index 2, and split it again to receive an array of characters:

const values = parts[2].split("");
raz-ezra
  • 514
  • 1
  • 15