如何用来自对象的值用javascript替换字符串中的特定部分 [英] How to replace specific parts in string with javascript with values from object

查看:43
本文介绍了如何用来自对象的值用javascript替换字符串中的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的 HTML 输出制作自定义替换方法.但我想不通.我想应该用 String.matchreplace 以某种方式完成.

I want to make custom replacer method for my HTML output. But I can't figure it out. I guess it should be done with String.match and replace somehow.

我的字符串中有一些错误代码",它们总是以 _err_ 开头,并且我有一个带有值的 JS 对象.

I have some "error codes" in my string that always start with _err_ and I have a JS object with values.

我想要达到的目标:

  1. 查找所有以 _err_ 开头的字符串部分(错误代码)
  2. 为我的对象获取正确的密钥 - 没有 _err_ 的错误代码
  3. 从 Lang 对象中寻找价值
  4. 用正确的 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"
};

我可以用其他方式来做.所以我循环 Lang 对象并替换字符串中的那些.如果使用下划线,它会是这样的:

I can do it other way around. So I cycle the Lang object and replace those in string. 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;
});

这假设您不希望替换诸如 "blah_err_blah" 之类的字符串,并且如果在您的 Lang 对象中找不到错误,则默认不替换文本.

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.

这篇关于如何用来自对象的值用javascript替换字符串中的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆