插值函数需要 [英] interpolate function need

查看:27
本文介绍了插值函数需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 javascript 函数,它可以像原型 js 框架那样进行插值.任何人都有不依赖原型的插值函数?欢迎使用jQuery.谢谢.

I need an javascript function that can do interpolate like the one for prototype js framework. Anyone have an interpolate function that is not depend on prototype? Jquery is welcome. Thanks.

推荐答案

根据您的需要,这样的事情可能会奏效:

Depending on your needs, something like this might work:

String.prototype.interpolate = function(valueMap){
  return this.replace(/\{([^}]+)\}/g, function(dummy, v){
    return valueMap[v];
  });
};

用法:

var params = {
  "speed":"slow",
  "color":"purple",
  "animal":"frog"
};
var template = "The {speed} {color} fox jumps over the lazy {animal}.";
alert(template.interpolate(params));

//alerts:
//"The slow purple fox jumps over the lazy frog."

这将为字符串中用大括号包裹的 {named} 项提供基本插值.

This will provide basic interpolation for {named} items wrapped in braces in your string.

注意:这是一个基本实现,不应在字符串或参数不安全的情况下使用(例如,如果您要构建 SQL 语句或其他内容)

Note: this is a basic implementation and shouldn't be used in cases where the string or parameters are not secure (e.g. if you were to build up a SQL statement or something)

这篇关于插值函数需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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