5

文字列内の各整数を、Key-Valueエントリに基づいてオブジェクト内の対応する値に変換しようとしています。たとえば、私が持っている場合:

var arr = {
    "3": "value_three",
    "6": "value_six",
    "234": "other_value"
  };
var str = "I want value 3 here and value 234 here";

出力を次のように拡張します。

new_str = "I want value_three here and value other_value here"
4

6 に答える 6

6

私はこれを頭のてっぺんからやっているだけですが、これはうまくいくはずです。

var new_str = str;

for (var key in arr) {
    if (!arr.hasOwnProperty(key)) {
        continue;
    }

    new_str = new_str.replace(key, arr[key]);
}

番号のすべての出現箇所を置き換えたい場合は、正規表現をミックスに組み込む必要があります。

var new_str = str;

for (var key in arr) {
    if (!arr.hasOwnProperty(key)) {
        continue;
    }

    new_str = new_str.replace(new RegExp(key, "g"), arr[key]);
}

arrまた、明らかにオブジェクトである場合は配列であることを意味するため、以外の名前を選択します。また、for-inプロトタイプのリークなどの問題があるため、配列ではなくオブジェクトでのみループを使用するようにしてください。

jQueryを使用してこれを行うこともできますが、おそらくやり過ぎです。

var new_str = str;

$.each(arr, function (key, value) {
    new_str = new_str.replace(key, value);
});
于 2012-06-26T01:19:37.470 に答える
3

のようなオブジェクトがarrあり、str定義およびnew_str宣言されているとします。次に、一般的な解決策を目指していると仮定すると、次のように機能します。

var arr = { "3": "value_three", "6": "value_six", "234": "other_value" };
var str = "I want value 3 here and value 234 here";

// Building a regex like `/3|6|234/g`
let re = new RegExp(Object.keys(arr).join('|'), 'g');

// Arrow function is approximately equivalent to
// an anonymous function like `function(match) { return arr[match]; }`
new_str = str.replace(re, match => arr[match]);

console.log(new_str);

ちょっとした補足として、arrあなたの例がObject。(私はそれらが連想配列と呼ばれることもあることを理解しています;それを指摘するだけです)。

于 2019-10-31T16:34:16.193 に答える
2

私の意見ではよりきれいに見えるレデューサーをここで使用することもできます:

new_str = Object.keys(dynamicValues).reduce((prev, current) => {
  return prev.replace(new RegExp(current, 'g'), dynamicValues[current]);
}, value);
于 2019-05-17T09:02:20.137 に答える
2

2021:

気をつけて

value 3

も一致します

value 32

const arr = {'3':'value_three', '6':'value_six', '234':'other_value'};
let str = 'I want value 3 here and value 234 here';

Object.keys(arr).forEach(key => str = str.replaceAll(`value ${key}`,arr[key]))
console.log(str)

于 2021-02-03T12:45:39.707 に答える
1

を使用するregexと、別の解決策は次のようになります。

const object = {
    "3": "value_three",
    "6": "value_six",
    "234": "other_value"
};
const str = "I want value 3 here and value 234 here. value 32";

const replacedText1 = str.replace(/value \d+/g, v=>object[v.split(" ")[1]] || v);

const replacedText2 = str.replace(/\d+/g, v=>object[v] || v);

console.log(replacedText1);
console.log(replacedText2);

于 2021-02-03T14:31:13.010 に答える
0

最近、文字列をオブジェクトのエントリに置き換える必要がありましたkey: value。一部のキーには、中括弧などの特殊文字が含まれています。したがって、他の人が示唆しているようにString.replace、置換値として関数を渡すRegExpで関数を使用できますが、RegExp自体を作成することには問題があります。これは、その中のすべての特殊文字を。でエスケープする必要があるため\です。エスケープ関数と最後の置換関数の例を次に示します。

// Escape string to use it in a regular expression
const regexpEscape = (string) => string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');

// Replace string with `key: value` entries of the search object.
const stringReplace = (string, search) => {
  const regexp = new RegExp(
    Object.keys(search)
      .map((item) => regexpEscape(item))
      .join('|'),
    'g'
  );
  return string.replace(regexp, (match) => search[match]);
};

const search = {
   '{{name}}': 'John',
   '{{lastname}}': 'Doe',
   '{{age}}': 24,
};

const template = 'Hey, {{name}} {{lastname}}! Your age is {{age}}.';

console.log(stringReplace(template, search));

それが誰かを助けることを願っています!おげんきで :)

于 2021-01-14T09:46:35.063 に答える