gpt4 book ai didi

JavaScript 分割字符串

转载 作者:行者123 更新时间:2023-11-28 15:23:57 24 4
gpt4 key购买 nike

请查看我的 JavaScript 代码:

var str = "/price  -a 20 tips   for model";
var removeSlsh = str.slice(1); //output = price -a 20 tips for model
var newStr = removeSlsh.replace(/\s+/g,' ').trim().split(' ');
console.log(newStr); // Output = ["price", "-a", "20", "tips", "for", "model"]

上面的代码工作正常。每个字符串都 split 有空间。但我需要像这样分割上面的字符串

1 = price  // Field name
2 = -a // price type -a anonymous, -m model, -p private
3 = 20 // amount of price
4 = tips for model //comment

输出应该是

["price", "-a", "20", "tips for model"]

编辑:

如果我设置分割文本的限制。看起来像

var newStr = removeSlsh.replace(/\s+/g,' ').trim().split(' ',4);
console.log(newStr); // Output = ["price", "-a", "20", "tips"]

注意 - 价格类型和注释是可选字段。字符串可以是 /price 20/price 20 Tips for model/price -a 20 但价格字段是强制性的,并且必须是数字值(value)。第二个字段是可选的,您不会输入任何值。如果您要输入除 -a、-m、-p 之外的任何文本,则此字段有效。

最佳答案

您不需要分割,而是提取部分,这可以使用正则表达式来完成:

var parts = str.match(/^\/(\S+)\s+(\S+)\s+(\S+)\s*(.*)/).slice(1);

结果:

["price", "-a", "20", "tips   for model"]

现在假设

  1. 您得到的字符串可能是错误的,
  2. 您想确保第三部分是数字,
  3. 参数 -a 或 -e 或 -something 是可选的,
  4. 最后一部分(注释)是可选的,

那么你可以使用这个:

var m = str.match(/^\/(\S+)(\s+-\w+)?\s+(-?\d+\.?\d*)\s*(.*)/);
if (m) {
// OK
var parts = m.slice(1); // do you really need this array ?
var fieldName = m[1]; // example: "price"
var priceType = m[2]; // example: "-a" or undefined
var price = +m[3]; // example: -23.41
va comments = m[4]; // example: "some comments"
...
} else {
// NOT OK
}

示例:

  • "/price -20 some comments"给出["price", undefined, "-20", "some comments"]

  • "/price -a 33.12"给出["price", "-a", "33.12", ""]

关于JavaScript 分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30029329/

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