我编写了一个函数来向HTML注入模板,而不使用像EJS,Mustache.js,Nunjucks,Pure.js等“大”模板引擎。
我使用键值对象传递这段代码:
<div><b>@{firstname} @{lastname}</b>, @{gender}</div>
现在我需要删除多余的空格,如果有人试图用“@ {firstname}”代替“@ {firstname}”。
我很抱歉,但我不知道如何编写正确的ReGex以删除空格。如何删除空格?
感谢您的支持。
更新: 感谢@Saleem的回答。这里有一个带有修复的演示: https://jsfiddle.net/avq3sntq/
答案 0 :(得分:2)
尝试以下正则表达式:
Random mRandom = new Random();
double[] weights = {0.3, 0.2, 0.1, 0.5}; //Make sure these sum to 1!! But at least you can change these at run-time.
int getRandomObject() {
double randNum = mRandom.nextDouble();
double sumOfWeightSoFar = 0;
int currentIndex = 0;
while (true) {
if (randNum < weights[currentIndex] + sumOfWeightSoFar)
return currentIndex;
else {
currentIndex++;
sumOfWeightSoFar = sumOfWeightSoFar + weights[currentIndex];
}
}
//If your weights don't sum to 1 or more, then "currentIndex" will eventually exceed your array bounds. But you get the idea.
}
如果输入字符串是:
result = subject.replace(/(@\{)\s*(\S+)\s*(?=})/img, "$1$2");
输出将是:
<div><b>@{ firstname } @{lastname}</b>, @{gender}</div>
如您所见,删除花括号内的第一个名称的所有额外空格。请参阅Demo此处