簡體   English   中英

從 Javascript 中的數組值替換字符串

[英]Replace a string from array values in Javascript

我正在嘗試將傳入值轉換如下

示例:輸入:00000016B Output:000000162

每當我在傳入輸入值的最后一個字符處看到下表中的“字符”時,我需要按照下表進行轉換。

1.我的輸入“00000016B”更改為“000000162” ,因為B應該替換為“+2”,所以輸入是正數,最后一個字符應該是“2”

2.我的輸入“00000016K”更改為“-000000162” ,因為K應該替換為“-2”,所以輸入是負數,最后一個字符應該是“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     |

我試過下面的代碼


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

最后總是給我零

這應該適合你:

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

它只是檢查 id 最后一個字符是否在列表中,然后將其附加到數字。

您可以通過抓取最后一個字符並在 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; }

我會寫一個簡單的 reg 表達式來匹配字符串,然后它是一個簡單的檢查,它應該是一個 + 或 -

 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"));

您正在過度使用解決方案,基本上您可以通過獲取值然后替換它,添加一個子句來添加或不添加-符號來做到這一點。

像這樣的 function 就可以完成這項工作:

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

在這里您可以找到一個工作示例,我使用了一個forEach來說明各種示例。

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

所以,我的方法有點不同。 一、不改標准替換全部為replaceAll 這不是一個好習慣。 然后,讓我們將您的數據視為object而不是array 所以是這樣的:

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

然后你需要一個返回轉換字符串的 function。 在我的想法中,我想到了一個 function ,它還告訴我們字符串中是否存在字符之一。 function可以是這樣的:

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

然后我們需要一個通用的轉換 function 來進行轉換並在需要時添加減號:

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

我為你創建了一個游樂場: https://jsfiddle.net/youdede/q47pst3L/31/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM