简体   繁体   English

如何使用对象值替换javascript字符串中的特定部分

[英]How to replace specific parts in string with javascript with values from object

I want to make custom replacer method for my HTML output. 我想为我的HTML输出制作自定义的替换方法。 But I can't figure it out. 但我不知道。 I guess it should be done with String.match and replace somehow. 我猜应该用String.match完成并replace某种方式replace

I have some "error codes" in my string that always start with _err_ and I have a JS object with values. 我的字符串中有一些“错误代码”,总是以_err_开头,并且有一个带有值的JS对象。

What I want to achieve: 我要实现的目标:

  1. Find all string parts (error codes) that starts with _err_ 查找以_err_开头的所有字符串部分(错误代码)
  2. Get correct key for my object - error code without _err_ 获取我的对象的正确密钥-不带_err_的错误代码
  3. Find value from Lang object 从Lang对象中寻找价值
  4. Replace error code with correct Lang value. 将错误代码替换为正确的Lang值。

Some error codes may appear multiple times. 某些错误代码可能会出现多次。

var content = "Looks like you have _err_no_email or _err_no_code provided";
var Lang = {
    'no_email' : "No email",
    'no_code' : "No code"
};

I can do it other way around. 我可以用其他方式来做。 So I cycle the Lang object and replace those in string. 因此,我循环了Lang对象,并将其替换为字符串。 It would be something like this if using underscore: 如果使用下划线,将类似于以下内容:

function replaceMe() {
    _.each(Lang, function(value, key) {
        content = content.replace(new RegExp('_err_' + key,'g'), value);
    });
    console.log(content);
};

But if it can be done faster with my first idea then I want to know how. 但是,如果我的第一个想法可以更快地完成,那么我想知道如何做。

A simple regex should do the trick: 一个简单的正则表达式应该可以解决问题:

var content = content.replace(/\b_err_(.+?)\b/g, function(match, errorName) {
    return Lang[errorName] || match;
});

This assumes that you do not want strings like "blah_err_blah" to be replaced, and defaults to not replacing the text if the error cannot be found in your Lang object. 这假定您不希望替换"blah_err_blah"类的字符串,并且默认情况下,如果在您的Lang对象中找不到错误,则不替换该文本。

var replace = function(str, object, regexp) { //if property not found string is not replaced
    return String(str).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name) {
        return (object[name] != null) ? object[name] : match;
    });
}

This is a format function I've used in several projects thats quite efficient. 这是我在多个项目中使用过的格式功能,非常有效。 Matches {prop} by default to {prop:'val'} but you can pass a regex for example maybe in your case /_err_+\\S/g so it matches other tokens in your string. 默认情况下,将{prop}与{prop:'val'}匹配,但是您可以传递一个正则表达式,例如在您的情况下/_err_+\\S/g ,使其与字符串中的其他标记匹配。

So you can do: 因此,您可以执行以下操作:

var content ="Looks like you have {no_email} or {no_code} provided";
var Lang = {
    'no_email' : "No email",
    'no_code' : "No code"
}

var formatted = replace(content, lang);

Or for your original string stealing the other answers regex: 或者为您的原始字符串窃取正则表达式的其他答案:

var formatted = replace(content, lang, /_err_([^\s]+)/g)

You can use a callback function, that look if a key matching the error code exists in your Lang object, and if so returns the value of that (and otherwise just the key itself, thereby doing no replacement, like so: 您可以使用一个回调函数,该函数查看Lang对象中是否存在与错误代码匹配的键,如果存在,则返回该键的值(否则仅返回键本身,因此不进行替换,如下所示:

content.replace(/_err_([a-z_]+)/gi, function(fullmatch, key) {
  return Lang[key] ? Lang[key] : fullmatch;
});

The first parameter passed to the function will be the full match, and the second parameter key will just be that part grouped by the bracktes. 传递给函数的第一个参数将是完全匹配项,而第二个参数key将只是由括号分组的那一部分。

And then, if Lang contains a (non-falsy) value for key , that'll be returned, otherwise just the fullmatch value, so that that part of the string gets “replaced” with itself. 然后,如果Lang包含key的(非伪造的)值,则将返回该值,否则将返回fullmatch值,以便字符串的该部分被自身“替换”。

See it in action here: http://jsfiddle.net/VZVLt/1/ 在此处查看其运行情况: http : //jsfiddle.net/VZVLt/1/

One more variation with split split一种变化

content = content
        .split('_err_')
        .map(function(str, index){
            if (index === 0) 
                return str;

            var whitespace = str.indexOf(' '),
                key = str.substring(0, whitespace)

            return Lang[key] + str.substring(whitespace);
        })
        .join('')
        ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM