tradersjoe
tradersjoe

Reputation: 37

Replace a string from array values in Javascript

I am trying to convert incoming values as below

Example: Input: 00000016B Output: 000000162

Whenever I see a "Character" from below table at the last character of a incoming input value, I need to convert as per below table.

1.My Input "00000016B" changed to "000000162" as B should be replaced by "+2", so the input is a positive number and last character should be a "2"

2.My Input "00000016K" changed to "-000000162" as K should be replaced by "-2", so the input is a negative number and last character should be a "2"

| Character | Value  |
| --------  | -------|
| {         | +0     |
| A         | +1     |
| B         | +2     |
| C         | +3     |
| D         | +4     |
| E         | +5     |
| F         | +6     |
| G         | +7     |
| H         | +8     |
| I         | +9     |
| }         | -0     |
| J         | -1     |
| K         | -2     |
| L         | -3     |
| M         | -4     |
| N         | -5     |
| O         | -6     |
| P         | -7     |
| Q         | -8     |
| R         | -9     |

I tried below code


    String.prototype.replaceAll = function(search, replacement) {
        var target = this;
        return target.replace(new RegExp(search, 'g'), replacement);
    };
    
    function replaceAll(QtyProcess, map){
        for(key in map){
            QtyProcess = QtyProcess.replaceAll(key, map[key]);
        }
        return QtyProcess;
    }
    
    var QtyProcess =  QtyTireDate.substr(8,9);
    var map = {
            '{': '+0',
            'A': '+1',
            'B': '+2',
            'C': '+3',
            'D': '+4',
            'E': '+5',
            'F': '+6',
            'G': '+7',
            'H': '+8',
            'I': '+9',
            '}': '-0',
            'J': '-1',
            'K': '-2',
            'L': '-3',
            'M': '-4',
            'N': '-5',
            'O': '-6',
            'P': '-7',
            'Q': '-8',
            'R': '-9'
    };
    var lastChar= replaceAll(QtyProcess, map);
    
    var lastNum = QtyProcess.substr (0,QtyProcess.length -1);
    
    if (lastChar.substr(0,1) == "-") {
      var QTYFinal = '-'+lastNum.concat(lastChar.substr(1,1));
    
    } else {
      var QTYFinal = lastNum.concat(lastChar.substr(1,1));
    
    }

It always gives me zero at the end

Upvotes: 0

Views: 474

Answers (5)

Francesco Lisandro
Francesco Lisandro

Reputation: 720

So, my approach is a bit different. First, do not change the standard replaceAll function. It's not a good practice. Then, let's consider your data like a object instead of an array. So something like this:

var map = {
    positive:['{','A','B','C','D','E','F','G','H','I'],
    negative:['}','J','K', 'L','M','N', 'O','P', 'Q','R']
}

Then you need a function that returns a converted string. In my idea, I thought about a function that tell us also if one of the char is present in our string. The function can be like this:

function convertFromArray(text,arr){
    let isPresent = false;
    arr.forEach((char,i)=>{
    if (text.includes(char)){
      text = text.replace(char, i);
      isPresent = true;
    }
  });
  return {isPresent,text};
}

Then we need a general convert function that does the conversion and add the minus symbol if it's needed:

function convert(text){
  let positiveResults = convertFromArray(text,map.positive);
  let negativeResults = convertFromArray(positiveResults.text,map.negative);
  return (negativeResults.isPresent)?'-'+negativeResults.text:positiveResults.text;
}

I created a playground for you: https://jsfiddle.net/youdede/q47pst3L/31/

Upvotes: 0

Prince Hernandez
Prince Hernandez

Reputation: 3721

you are overkilling the solution, basically you can do it by getting the value and then replace it, adding a clause to add or not the - signe.

just a function like this would do the job:

const replaceChar = (str) => {
  // get the char to replace
  const char = str.substr(8, 9);
  // get the value of the character to replace
  const mapValue = map[char];
  // get the signe and the value to use on the string
  const [signe, value] = mapValue.split("");
  // first replace the character for the new value
  const replaced = str.replace(char, value);
  // now lets check if we need the signe or not
  const start = signe === '+' ? '' : '-';

  return start + replaced;
}

here you can find a working example, I used a forEach to illustrate various examples.

var strings = [
  '00000016B',
  '00000016H',
  '00000016A',
  '00000016D',
  '00000016}',
  '00000016P',
  '00000016K',
]
var map = {
  '{': '+0',
  'A': '+1',
  'B': '+2',
  'C': '+3',
  'D': '+4',
  'E': '+5',
  'F': '+6',
  'G': '+7',
  'H': '+8',
  'I': '+9',
  '}': '-0',
  'J': '-1',
  'K': '-2',
  'L': '-3',
  'M': '-4',
  'N': '-5',
  'O': '-6',
  'P': '-7',
  'Q': '-8',
  'R': '-9'
};


const replaceChar = (str) => {
  // get the char to replace
  const char = str.substr(8, 9);
  // get the value of the character to replace
  const mapValue = map[char];
  // get the signe and the value to use on the string
  const [signe, value] = mapValue.split("");
  // first replace the character for the new value
  const replaced = str.replace(char, value);
  // now lets check if we need the signe or not
  const start = signe === '+' ? '' : '-';

  return start + replaced;
}


strings.forEach(str => {
  console.log(str, " --> ", replaceChar(str));
})

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48610

You can look it up by grabbing the last character and looking it up in the map.

const charMap = {
  '{': +0,  'A': +1,  'B': +2,  'C': +3,  'D': +4,  'E': +5,  'F': +6,
  'G': +7,  'H': +8,  'I': +9,  '}': -0,  'J': -1,  'K': -2,  'L': -3,
  'M': -4,  'N': -5,  'O': -6,  'P': -7,  'Q': -8,  'R': -9
}

const
  fix = (str) =>
    ((head, last) =>
      (found =>
        `${found < 0 ? '-' : ''}${head}${!isNaN(found) ? Math.abs(found) : last}`)
      (charMap[last]))
    (str.substring(0, str.length - 1), str.charAt(str.length - 1)),
  fixAll = (...vargs) => vargs.map(fix);

console.log(fix('00000016B')); //  000000162
console.log(fix('00000016K')); // -000000162
console.log(fix('00000016Z')); //  00000016Z (Unknown)

fixAll(
  '00000016{', //  000000160
  '00000016O', // -000000166
  '00000016R'  // -000000169
).forEach(res => console.log(res));
.as-onsole-wrapper { top: 0; max-height: 100% !important; }

Upvotes: 0

epascarello
epascarello

Reputation: 207511

I would write a simple reg expression to match the string and then it is a simple check to see it it should be a + or -

var map = {
  '{': '+0',
  'A': '+1',
  'B': '+2',
  'C': '+3',
  'D': '+4',
  'E': '+5',
  'F': '+6',
  'G': '+7',
  'H': '+8',
  'I': '+9',
  '}': '-0',
  'J': '-1',
  'K': '-2',
  'L': '-3',
  'M': '-4',
  'N': '-5',
  'O': '-6',
  'P': '-7',
  'Q': '-8',
  'R': '-9'
};

function updateMyString(str) {
  return str.replace(/^(-?)(.+)(.)$/, function(_, sign, mid, char) {
    const repl = (map[char] || '+' + char).match(/([-+])(\d+)/);
    const updatedSign = (repl[1] === '+') ? sign : (sign === "-") ? '' : '-';
    return updatedSign + mid + repl[2];
  });
}

console.log("00000016B", updateMyString("00000016B"));
console.log("-00000016B", updateMyString("-00000016B"));
console.log("00000016K", updateMyString("00000016K"));
console.log("-00000016K", updateMyString("-00000016K"));

Upvotes: 0

nilsf
nilsf

Reputation: 138

This should work for you:

var map = {
    "{": "+0",
    A: "+1",
    B: "+2",
    C: "+3",
    D: "+4",
    E: "+5",
    F: "+6",
    G: "+7",
    H: "+8",
    I: "+9",
    "}": "-0",
    J: "-1",
    K: "-2",
    L: "-3",
    M: "-4",
    N: "-5",
    O: "-6",
    P: "-7",
    Q: "-8",
    R: "-9",
};

var input = "00000016}";
var last_char = input.slice(-1);
if (last_char in map) {
    if (map[last_char].slice(0,1) == "-") {
        output = "-" + input.slice(0, -1) + map[last_char].slice(-1);
    } else {
        output = input.slice(0, -1) + map[last_char].slice(-1);
    }
    console.log(output);
}

It just checks id the last character is in the list and then appends it to the number.

Upvotes: 2

Related Questions