gpt4 book ai didi

javascript - 从价格中去除美元符号

转载 作者:可可西里 更新时间:2023-11-01 01:28:58 25 4
gpt4 key购买 nike

我正在构建一串金额,但需要删除美元符号。我有这个 jQuery 代码:

  buildList($('.productPriceID > .productitemcell'), 'pricelist')

它回来了

pricelist=$15.00,$19.50,$29.50

我需要删除美元符号,但似乎无法弄清楚。尝试使用 .trim,但我认为这只会删除空格。

抱歉新手问题!在此先感谢您的帮助!

完整代码如下:

function buildList(items, name) {
var values = [];
items.each(function() {
values.push(this.value || $(this).text());
});
return name + '=' + values.join(',');
}

var result = [
buildList($('.productCodeID > .productitemcell'), 'skulist'),
buildList($('.productQuantityID > .productitemcell > input'), 'quantitylist'),
buildList($('.productPriceID > .productitemcell'), 'pricelist')
];

var string = result.join('&');

这是javascript运行前的原始代码

<span class="productPriceID">
<div class="productitemcell">$15.00</div>
<div class="productitemcell">$19.50</div>
<div class="productitemcell">$29.50</div>
</span>

最佳答案

编辑:现在我有了正在运行的代码,从答案开始。

查看更新后的代码,这应该可以工作:

示例: http://jsbin.com/ekege3/

var result = [
buildList($('.productCodeID > .productitemcell'), 'skulist'),
buildList($('.productQuantityID > .productitemcell > input'), 'quantitylist'),
buildList($('.productPriceID > .productitemcell'), 'pricelist')
];

result[ 2 ] = result[ 2 ].replace(/\$/g, '');

var string = result.join('&');

旁注:您可以像这样缩短您的 buildList 函数:

function buildList(items, name) {
return (name + '=') + items.map(function() {
return (this.value || $(this).text());
}).get().join(',');
}

原回答:

如果您有字符串,只需使用 .replace()

var str = "pricelist=$15.00,$19.50,$29.50";

str = str.replace(/\$/g, '');

或者您是说您有一个包含数组的变量 pricelist?如果是这样,请执行以下操作:

var pricelist = ["$15.00","$19.50","$29.50"];

for( var i = 0, len = pricelist.length; i < len; i++ ) {
pricelist[ i ] = pricelist[ i ].replace('$', '');
}

编辑:听起来好像 buildList 方法返回一个数组。

一种检查方法是这样做:

alert( Object.prototype.toString.call( result[2] ) );

看看它给你带来了什么。

无论如何,假设它是一个数组,这是第二个示例的更新版本。

var result = [
buildList($('.productCodeID > .productitemcell'), 'skulist'),
buildList($('.productQuantityID > .productitemcell > input'), 'quantitylist'),
buildList($('.productPriceID > .productitemcell'), 'pricelist')
];

// verify the data type
alert( Object.prototype.toString.call( result[ 2 ] ) );

// loop over result[ 2 ], replacing the $ with ''
for( var i = 0, len = result[ 2 ].length; i < len; i++ ) {
result[ 2 ][ i ] = result[ 2 ][ i ].replace('$', '');
}

var string = result.join('&');

关于javascript - 从价格中去除美元符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4209130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com