javascript中的任何类似于ruby的#{value}(字符串插值) [英] Anything similar in javascript to ruby's #{value} (string interpolation)
问题描述
我厌倦了写这个:
string_needed =prefix .....+ topic +suffix ... 。+ name +测试;
string_needed="prefix....." + topic + "suffix...." + name + "testing";
我认为有人可能已经对此做了一些事情;)
i would think someone might have done something about this by now ;)
推荐答案
ES6更新:
ES6添加模板字符串,使用反引号(`)而不是单引号或双引号。在模板字符串中,您可以使用 $ {}
语法来添加表达式。使用你的例子,它将是:
ES6 Update:
ES6 added template strings, which use backticks (`) instead of single or double quotes. In a template string, you can use the ${}
syntax to add expressions. Using your example, it would be:
string_needed = `prefix.....${topic}suffix....${name}testing`
原始答案:
抱歉:(
Original answer:
Sorry :(
我喜欢利用Array.join:
I like to take advantage of Array.join:
["prefix ....", topic, "suffix....", name, "testing"].join("")
或使用 String.concat
String.concat("a", 2, "c")
或者您可以编写自己的连接函数:
or you could write your own concatenate function:
var concat = function(/* args */) {
/*
* Something involving a loop through arguments
*/
}
或使用第三方 sprintf
功能,例如 http://www.diveintojavascript.com/projects/javascript-sprintf
or use a 3rd-party sprintf
function, such as http://www.diveintojavascript.com/projects/javascript-sprintf
这篇关于javascript中的任何类似于ruby的#{value}(字符串插值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!