1

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;
 }
4
  • remove the #? and change it to # and your all good! Commented Jan 14, 2022 at 3:32
  • please edit your question Commented Jan 14, 2022 at 4:07
  • @SolomonPByer thanks for reply, updated the question Commented Jan 14, 2022 at 4:14
  • .replace(/^#?(\d+)(?=-\d)/, (_,$1) => $1.padStart(2,"0")) seems working well enough. Commented Jan 14, 2022 at 8:39

4 Answers 4

1

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).
Sign up to request clarification or add additional context in comments.

8 Comments

thanks for helping , #6-764 78798 should be 06-764 78798 but returns same
@sen It returns #6-764 78798 => 06-764 78798
apologies 78798 #6-764 should be 78798 06-764 but returns same
the above code does not work for 380100 6-764, 380100 #6-764, 380100 #06-764 for these should return 380100 06-764
@sen It's my pleasure. I only missed the "anywhere inside a string" bit. If you have problems with the word boundary, replace with (?<!\d). Or let me know.
|
1

Using the unary operator, here's a two liner replacer function.

const testValues = ["#162-7878", "#12-4598866", "#1-7878", "1-7878"];
const re = /#?(\d+?)-(\d+)/;

for(const str of testValues) {
  console.log(str.replace(re, replacer));
}

function replacer(match, p1, p2) {
  p1 = +p1 < 10 ? `0${p1}` : p1;
  return `${p1}-${p2}`; 
}

5 Comments

hanks for helping but when i pass 1-7878 should be 01-7878
@sen Adjusted answer.
thanks for reply again but its not working for #02-7878 changes to 002-7878 instead of 02-7878
@sen You posted some code in the question: is it working fine for you? If yes, what do you need?
thanks for reply, this scenario ->string like "2-7878" to "02-7878" works when i try #02-7878 its not working, it shows 002-7878 instead of 02-7878 .
0
let list_of_numbers =["#1-7878", "#162-7878", "#12-1676","#02-8989898","#676-98908098","12-232","02-898988","676-98098","2-898988"]

const solution = () => {
    let result = ''
    for (let number of list_of_numbers) {
        let nums = number.split('-')
        if (nums[0][0] == '#' && nums[0].length > 2) {
            result = `${nums[0].slice(1, number.length-1)}-${nums[1]}`
            console.log(result)
        } else if (nums[0][0] == '#' && nums[0].length == 2) {
            result = `${nums[0][0] = '0'}${nums[0][1]}-${nums[1]}`
            console.log(result)
        } else {
            console.log(number)
        }
    }
}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

I think a simple check is what you should do with the match function.

let arrstr=["#12-1676","#0-8989898","#676-98908098","12-232","02-898988","676-98098","2-898988"];
const regex = /#\d-/g;
for(i in arrstr){
    var found = arrstr[i].match(regex);
    if(found){
      arrstr[i]=arrstr[i].replace("#","0")
    }else{
      arrstr[i]=arrstr[i].replace("#","")
    }
}
console.log(arrstr);

or if you really want to stick with the way you have it.

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

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;
 }

remove the '?' from the regex so its not #? but just #

3 Comments

thanks but when i pass 2-898988 should be 02-898988
then what isn't working about your code?
It works, but if there is no # and single digit before by hyphen, add only 0, not working, updated the question, apologies for missing out, thanks for helping

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.