更确切说是类似 Elixir 的 Sigils 特性:
defmodule MySigils do
def sigil_i(string, []), do: String.to_integer(string)
def sigil_i(string, [?n]), do: -String.to_integer(string)
end
import MySigils
IO.puts ~i/13/ # output: 13
IO.puts ~i/42/n # output: -42
https://hexdocs.pm/elixir/sigils.html
JavaScript 对应的 Tagged templates 相比 Sigils 没那么灵活,不过在字符处理上的效果基本一致:
const person = "Mike";
const age = 28;
function myTag(strings, personExp, ageExp) {
const str0 = strings[0]; // "That "
const str1 = strings[1]; // " is a "
const str2 = strings[2]; // "."
const ageStr = ageExp < 100 ? "youngster" : "centenarian";
return `${str0}${personExp}${str1}${ageStr}${str2}`;
}
const output = myTag`That ${person} is a ${age}.`;
console.log(output);
// That Mike is a youngster.