Skip to content
Advertisement

regex replace for multiple string array javascript

I have a array of string and the patterns like #number-number anywhere inside a string.

Requirements:

  • If the # and single digit number before by hyphen then replace # and add 0. For example, #162-7878 => 162-7878, #12-4598866 => 12-4598866

  • If the # and two or more digit number before by hyphen then replace remove #. For example, #1-7878 => 01-7878.

  • If there is no # and single digit number before by hyphen then add 0. For example, 1-7878 => 01-7878.

I got stuck and how to do in JavaScript. Here is the code I used:

let arrstr=["#12-1676","#02-8989898","#676-98908098","12-232","02-898988","676-98098","2-898988", "380100 6-764","380100 #6-764","380100 #06-764"]

for(let st of arrstr)
 console.log(st.replace(/#?(d)?(d-)/g ,replacer))
 
 function replacer(match, p1, p2, offset, string){
  let replaceSubString = p1 || "0";
  replaceSubString += p2;
  return replaceSubString;
 }

Advertisement

Answer

I suggest matching # optionally at the start of string, and then capture one or more digits before - + a digit to later pad those digits with leading zeros and omit the leading # in the result:

st.replace(/#?b(d+)(?=-d)/g, (_,$1) => $1.padStart(2,"0"))

See the JavaScript demo:

let arrstr=["#12-1676","#02-8989898","#676-98908098","12-232","02-898988","676-98098","2-898988", "380100 6-764","380100 #6-764","380100 #06-764"]

for(let st of arrstr)
 console.log(st,'=>', st.replace(/#?b(d+)(?=-d)/g, (_,$1) => $1.padStart(2,"0") ))

The /#?b(d+)(?=-d)/g regex matches all occurrences of

  • #? – an optional # char
  • b – word boundary
  • (d+) – Capturing group 1: one or more digits…
  • (?=-d) – that must be followed with a - and a digit (this is a positive lookahead that only checks if its pattern matches immediately to the right of the current location without actually consuming the matched text).
Advertisement