首页 > 解决方案 > Javascripts字符串比较和更新

问题描述

我正在尝试实现这个接收2个字符串作为参数的函数,这个函数需要比较第一个和第二个字符串,获取/保存差异,然后它应该将差异添加到第一个。我会更好地解释我:

我有var str1 = "abbccc"var str2 = "aabbbbd"现在我需要得到的是str3 = aabbbbcccd

我怎样才能做到这一点?我为我的英语不好为自己辩解,但我真的需要知道如何做到这一点。

更新:

第一个字符串如下所示:

const BaseModel = require("./baseModel");
const MTYPE = require("../lib/types");
const TOOLS = require("../lib/toolkit");
const CONSTANTS = require("../lib/constants");

/**
 * @description
 * ### CRM ###
   Model per la gestione dei soggetti: clienti/fornitori/destinazioni
 */

const xdKeyCliente = "clienti";
const xdKeyLead = "leads";
const xdKeyFornitore = "fornitori";
const xdKeyAgente = "agenti";
const xdKeyDestinazione = "destinazioni";
const xdKeyContatto = "contatti";
const xdKeyRivenditore = "rivenditori";
const xdKeyGruppiUtente = "gruppi_utente";
const xdKeyUtente = "utenti";
const xdKeyProspect = "prospects";

class SoggettiModel extends BaseModel {


    constructor(baseObject, callbackNotification) {

        var prop = {
            fields: {
                // #region CAMPI DB
                uuid: {
                    type: MTYPE.UUID,
                    allowNull: false,
                    primaryKey: true,
                    max: 16,
                    default: 'DEFAULT',
                },
            table: 'soggetti',
            odbcKey: 'DEFAULT',
            entity: "soggetti",
            principalFields: ["uuid", "ragsoc", "pfNome", "pfCognome", "indir", "local", "cap", "prov", "stato", "telefono", "email", "cellulare", "iTipo", "iTipoDescrizione", "iStatoDescrizione", "iProvinciaDescrizione", "iRuoloDescrizione", "iProvinciaCodice", "iNominativo", "iGestore", "iLinkedId", "iLinkedDescrizione", "iLinkedTipo", "obsoleto"],
            callbackNotification: callbackNotification,
        }

        super(prop, baseObject);
    }


    /**
     * Metodo per estrarre il soggetto di fatturazione.
     * Se � una destinazione ti ritorna il cliente, se � una filiale ritorna il gestore, se � un cliente ritorna il cliente stesso
     * @param {uuid} uuid
     * @param {any} isCliente: posso passare 0
     */
    async getClienteIfDestinazione(uuid, isCliente = "") {
        let cliente = "";

        let result = await this.executeFindByAttributes([{ "C": "uuid", "V": uuid }, { "OL": "AND" },
            { "P": "(" },
            { "C": "tipo", "V": "C" },
            { "OL": "OR" },
            { "P": "(" },
            { "C": "tipo", "O": "IN", "V": TOOLS.set_as_column("('D', 'I')") },
            { "OL": "AND" },
            { "C": "linktotype", "V": "C" },
            { "P": ")" },
            { "OL": "OR" },
            { "P": "(" },
            { "C": TOOLS.set_as_column(this.normString(isCliente)), "V": "0" },
            { "OL": "AND" },
            { "C": "tipo", "V": "L" },
            { "P": ")" },
            { "P": ")" },
        ], [], [], [TOOLS.set_as_column("CASE WHEN " + this.normString(isCliente) + " = '0' AND tipo = 'L' THEN uuid WHEN tipo = 'C' and id_gestore is null THEN uuid WHEN tipo = 'C' AND id_gestore IS NOT NULL THEN id_gestore WHEN tipo in ('D', 'I') THEN linktoid ELSE NULL END AS cliente")]);
        if (result.length > 0) {
            cliente = result[0]["cliente"];
        }

        if (cliente == null) {
            cliente = "";
        }

        return cliente;
    }


    /**
     * Ritorna l'xdkey per gli allegati data la tipologia del soggetto (C: cliente, L: lead, F: fornitore)
     * @param {string} tipo
     */
    getXdKey(tipo) {
        let xdKey = "";
        if (tipo == "C" || tipo == "I") {
            xdKey = xdKeyCliente;
        }
        else if (tipo == "L") {
            xdKey = xdKeyLead;
        }
        else if (tipo == "F") {
            xdKey = xdKeyFornitore;
        }
        else if (tipo == "A") {
            xdKey = xdKeyAgente;
        }
        else if (tipo == "D" || tipo=="M") {
            xdKey = xdKeyDestinazione;
        }
        else if (tipo == "N") {
            xdKey = xdKeyContatto;
        }
        else if (tipo == "R") {
            xdKey = xdKeyRivenditore;
        }
        else if (tipo == "G") {
            entity = xdKeyGruppiUtente;
        }
        else if (tipo == "U") {
            entity = xdKeyUtente;
        }
        else if (tipo == "K") {
            entity = xdKeyProspect;
        }

        return xdKey
    }


    /**
    * Ritorna l'entit� per gli allegati data la tipologia del soggetto (C: cliente, L: lead, F: fornitore)
    * @param {string} tipo
    */
    getEntity(tipo) {
        let entity = "";
        if (tipo == "C" || tipo == "I") {
            entity = "clienti";
        }
        else if (tipo == "L") {
            entity = "leads";
        }
        else if (tipo == "F") {
            entity = "fornitori";
        }
        else if (tipo == "A") {
            entity = "agenti";
        }
        else if (tipo == "D" || tipo == "M") {
            entity = "destinazioni";
        }
        else if (tipo == "N") {
            entity = "contatti";
        }
        else if (tipo == "R") {
            entity = "rivenditori";
        }
        else if (tipo == "G") {
            entity = "gruppiutenti";
        }
        else if (tipo == "U") {
            entity = "utenti";
        }
        else if (tipo == "K") {
            entity = "prospects";
        }

        return entity
    }

    /**
     * Estrae l'utente dato l'uuid registry
     */
    async getUtenteByUuid() {
        return await this.executeFindByPk(this.registryId);
    }
}

module.exports = SoggettiModel;

否则我的第二个是这样的:

const BaseModel = require("./baseModel");
const MTYPE = require("../lib/types");

/**
 * @description
 * ###  ###
   Model per la gestione dei soggetti: clienti/fornitori/destinazioni
 */

class SoggettiModel extends BaseModel {

    constructor(baseObject) {
        var prop = {
            fields: {
                // #region CAMPI DB

                newFiled: {
                    type: MTYPE.INTEGER,
                    allowNull: false,
                    primaryKey: true,
                    max: 16,
                    default: 'DEFAULT',
                }
            },
            table: 'soggetti',
            odbcKey: 'DEFAULT',
        }

        super(prop, baseObject);
    }
}

module.exports = SoggettiModel;

我需要得到的字符串是这样的:

const BaseModel = require("./baseModel");
const MTYPE = require("../lib/types");
const TOOLS = require("../lib/toolkit");
const CONSTANTS = require("../lib/constants");

/**
 * @description
 * ### CRM ###
   Model per la gestione dei soggetti: clienti/fornitori/destinazioni
 */

const xdKeyCliente = "clienti";
const xdKeyLead = "leads";
const xdKeyFornitore = "fornitori";
const xdKeyAgente = "agenti";
const xdKeyDestinazione = "destinazioni";
const xdKeyContatto = "contatti";
const xdKeyRivenditore = "rivenditori";
const xdKeyGruppiUtente = "gruppi_utente";
const xdKeyUtente = "utenti";
const xdKeyProspect = "prospects";

class SoggettiModel extends BaseModel {


    constructor(baseObject, callbackNotification) {

        var prop = {
            fields: {
                // #region CAMPI DB
                uuid: {
                    type: MTYPE.UUID,
                    allowNull: false,
                    primaryKey: true,
                    max: 16,
                    default: 'DEFAULT',
                },
                newFiled: {
                    type: MTYPE.INTEGER,
                    allowNull: false,
                    primaryKey: true,
                    max: 16,
                    default: 'DEFAULT',
                }
            }
            table: 'soggetti',
            odbcKey: 'DEFAULT',
            entity: "soggetti",
            principalFields: ["uuid", "ragsoc", "pfNome", "pfCognome", "indir", "local", "cap", "prov", "stato", "telefono", "email", "cellulare", "iTipo", "iTipoDescrizione", "iStatoDescrizione", "iProvinciaDescrizione", "iRuoloDescrizione", "iProvinciaCodice", "iNominativo", "iGestore", "iLinkedId", "iLinkedDescrizione", "iLinkedTipo", "obsoleto"],
            callbackNotification: callbackNotification,
        }

        super(prop, baseObject);
    }


    /**
     * Metodo per estrarre il soggetto di fatturazione.
     * Se � una destinazione ti ritorna il cliente, se � una filiale ritorna il gestore, se � un cliente ritorna il cliente stesso
     * @param {uuid} uuid
     * @param {any} isCliente: posso passare 0
     */
    async getClienteIfDestinazione(uuid, isCliente = "") {
        let cliente = "";

        let result = await this.executeFindByAttributes([{ "C": "uuid", "V": uuid }, { "OL": "AND" },
            { "P": "(" },
            { "C": "tipo", "V": "C" },
            { "OL": "OR" },
            { "P": "(" },
            { "C": "tipo", "O": "IN", "V": TOOLS.set_as_column("('D', 'I')") },
            { "OL": "AND" },
            { "C": "linktotype", "V": "C" },
            { "P": ")" },
            { "OL": "OR" },
            { "P": "(" },
            { "C": TOOLS.set_as_column(this.normString(isCliente)), "V": "0" },
            { "OL": "AND" },
            { "C": "tipo", "V": "L" },
            { "P": ")" },
            { "P": ")" },
        ], [], [], [TOOLS.set_as_column("CASE WHEN " + this.normString(isCliente) + " = '0' AND tipo = 'L' THEN uuid WHEN tipo = 'C' and id_gestore is null THEN uuid WHEN tipo = 'C' AND id_gestore IS NOT NULL THEN id_gestore WHEN tipo in ('D', 'I') THEN linktoid ELSE NULL END AS cliente")]);
        if (result.length > 0) {
            cliente = result[0]["cliente"];
        }

        if (cliente == null) {
            cliente = "";
        }

        return cliente;
    }


    /**
     * Ritorna l'xdkey per gli allegati data la tipologia del soggetto (C: cliente, L: lead, F: fornitore)
     * @param {string} tipo
     */
    getXdKey(tipo) {
        let xdKey = "";
        if (tipo == "C" || tipo == "I") {
            xdKey = xdKeyCliente;
        }
        else if (tipo == "L") {
            xdKey = xdKeyLead;
        }
        else if (tipo == "F") {
            xdKey = xdKeyFornitore;
        }
        else if (tipo == "A") {
            xdKey = xdKeyAgente;
        }
        else if (tipo == "D" || tipo=="M") {
            xdKey = xdKeyDestinazione;
        }
        else if (tipo == "N") {
            xdKey = xdKeyContatto;
        }
        else if (tipo == "R") {
            xdKey = xdKeyRivenditore;
        }
        else if (tipo == "G") {
            entity = xdKeyGruppiUtente;
        }
        else if (tipo == "U") {
            entity = xdKeyUtente;
        }
        else if (tipo == "K") {
            entity = xdKeyProspect;
        }

        return xdKey
    }


    /**
    * Ritorna l'entit� per gli allegati data la tipologia del soggetto (C: cliente, L: lead, F: fornitore)
    * @param {string} tipo
    */
    getEntity(tipo) {
        let entity = "";
        if (tipo == "C" || tipo == "I") {
            entity = "clienti";
        }
        else if (tipo == "L") {
            entity = "leads";
        }
        else if (tipo == "F") {
            entity = "fornitori";
        }
        else if (tipo == "A") {
            entity = "agenti";
        }
        else if (tipo == "D" || tipo == "M") {
            entity = "destinazioni";
        }
        else if (tipo == "N") {
            entity = "contatti";
        }
        else if (tipo == "R") {
            entity = "rivenditori";
        }
        else if (tipo == "G") {
            entity = "gruppiutenti";
        }
        else if (tipo == "U") {
            entity = "utenti";
        }
        else if (tipo == "K") {
            entity = "prospects";
        }

        return entity
    }

    /**
     * Estrae l'utente dato l'uuid registry
     */
    async getUtenteByUuid() {
        return await this.executeFindByPk(this.registryId);
    }
}

module.exports = SoggettiModel;

注意:这些类包含在一个字符串中,我将它们写成片段以便您更好地理解。

标签: javascriptnode.jsstring

解决方案


您可以使用将字符串转换为列表string.split(""),然后遍历列表。如果条目相同,则从一个字符串中添加条目,如果它们不同,则将两个条目添加到字符串中。如果一个字符串长于将剩余条目添加到输出字符串中,我尝试按照我理解的问题构建它,可能有一种更漂亮/更好的方法,但这可能有助于解决您的问题

  var str1 = "abbccc"
  var str2 = "aabbbbd"
  var out = ""
  var i =0;

  var longer = (str1.length > str2.length ? str1.length : str2.length)
 
 for(i=0;i<longer;i++){
    str1[i] == str2[i] ? out += str1[i] : str1[i] != undefined && str2[i] != undefined ? out += (str1[i] + str2[i]) : ""
    str1[i] == null ? out += str2[i] : ""
    str2[i] == null ? out += str1[i] : ""
  }

  out = out.split("").sort().join("").toString() // Only if you need the string to be in alphabetical order
  
  console.log(out)


推荐阅读