我有一个数据库填充的行,根据输入的内容需要不同的格式。有三种格式:
线示例1)$ 3.00
线示例1)每人两个$ 4.95
线示例2)小$ 5.00 |中等$ 10.00 |大$ 15.00
第1行)无需更改
第2行)需要在$
之前插入额外的空格
第3行)需要在|之前和之后插入额外的空格但不是在$(所有情况)之前
我环顾四周,试图将事情拼凑在一起,但却无法得到它。以下是我到目前为止的情况:
$('.menu-price-value:contains("$")').each(function() {
var newText = $(this).html().replace('$', '<span class="space"></span>$');
$(this).html(newText);
});
$('.menu-price-value:contains("|")').each(function() {
var newText = $(this).html().replace("|", " | ");
$(this).html(newText);
$('.menu-price-value').addClass('remove-space');
});
&#13;
答案 0 :(得分:0)
使用regexp查找所需的模式,然后使用字符串:
function myparser(text){
if (matches=text.match(/^([^|$])+\$(\d+(\.\d+))$/i))
return matches[1]+" $"+matches[2];
else if (text.match(/\|/))
{
var myArray=text.split("|");
var toReturn="";
for (var i in myArray)
{
toReturn+=myArray[i]+" "+"|"+" ";
}
return toReturn;
}
else
return text;
}
该函数检测字符串的类型,然后将其恢复为固定。
看到它起作用: 的 FIDDLE 强>
答案 1 :(得分:0)
有一些问题
replace
仅替换第一场比赛(我知道比较蹩脚)。使用带有g
(全局)选项的正则表达式替换所有出现。JSFiddle:http://jsfiddle.net/TrueBlueAussie/evn91m7y/1/
$('.menu-price-value:contains(" $")').html(function () {
return $(this).html().replace(/\$/g, '<span class="space"> </span>$');
});
$('.menu-price-value:contains("|")').html(function () {
return $(this).html().replace(/\|/g, " | ");
}).addClass('remove-space');
为避免对$
个匹配项进行|
检查,您可以像这样添加:not(contains("|"))
:
$('.menu-price-value:contains(" $"):not(:contains("|"))').html(function () {
return $(this).html().replace(/\$/g, '<span class="space"> </span>$');
});
e.g。 http://jsfiddle.net/TrueBlueAussie/evn91m7y/2/
甚至只需将.not()
html()
的检查顺序和链选择器反转:http://jsfiddle.net/TrueBlueAussie/evn91m7y/4/
注释:
$
的函数,该函数将html替换为每个元素的返回值。$
之前有一个空格。另一种方法是查看值以 space
开头的值。