【问题标题】:How to remove a part of a string which will always be at the last?如何删除始终位于最后的字符串的一部分?
【发布时间】:2022-01-04 17:57:38
【问题描述】:

我做了一个函数,它删除字符串的最后一部分,它总是从_ 开始并获取整数,但我得到的只是文本部分而不是整数

如何做到这一点?

function splitLast(arg) {
  if (arg.includes(".") && arg.includes("_")) {
    return parseFloat(arg.split("_").pop())
  } else if (arg.includes(".") != true && arg.includes("_")) {
    return parseInt(+arg.split("_").pop())
  } else {
    throw "Arguments passed does not contain the valid result characters or isnt a required Datatype for thefunction"
  }
}

console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')

【问题讨论】:

  • 您说字符串“从_开始”并且您想“获取整数”,但是在您自己的示例代码中,“_”之后的文本是“no”,它不是整数。
  • 您的代码也应该以文本的形式发布在这里,而不是图像。
  • 最后一部分,即字符串分为两部分,第一部分是整数,第二部分是文本,所以文本总是以 _ 开头,然后是文本之后的所有内容
  • "22.1_no".split("_").pop() 将返回字符串“no”。 "22.1_no".split("_") 返回数组 ["22.1", "no"]
  • 这样是不是像 return parseInt(arg[0])

标签: javascript arrays string


【解决方案1】:

UPD:更好的解决方案

您可以使用parseFloat() 函数而无需额外的检查和字符串解析(它会为您完成这一切):

function splitLast(arg) {
  if (isNaN(arg.trim()[0])) {
    throw new Error('argument is not valid')
  }

  return parseFloat(arg)
}

console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')
console.log(splitLast("a22.1_no"), 'should throw')
console.log(splitLast("  a22.1_no"), 'should throw')

isNaN() 需要检查,因为parseFloat(string) 返回:

  1. 从给定字符串解析的浮点数(这正是您所需要的)
  2. NaN,当第一个非空白字符无法转换为数字时(这是一种极端情况,但我们应该知道)

旧解决方案:

您可能必须使用shift() 方法而不是pop()


pop() 方法从数组中删除最后一个元素并返回该元素。这个方法改变了数组的长度。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

shift() 方法从数组中移除第一个元素并返回移除的元素。这个方法改变了数组的长度。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift


function splitLast(arg) {
  if (arg.includes(".") && arg.includes("_")) {
    return parseFloat(arg.split("_").shift())
  } else if (arg.includes(".") != true && arg.includes("_")) {
    return parseInt(arg.split("_").shift())
  } else {
    throw "Arguments passed does not contain the valid result characters or isnt a required Datatype for thefunction"
  }
}

console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')

【讨论】:

    【解决方案2】:

    您可以使用正则表达式和.replace:

    function splitLast(value) {
      return value.replace(/_.*$/, '');
    }
    
    console.log(splitLast("22_no"), 'should be 22')
    console.log(splitLast("22.1_no"), 'should be 22.1')

    【讨论】:

      【解决方案3】:

      您可以使用它从字符串中删除文本,只保留带下划线的数字。

       var ret = "22.1_no";
          var str = ret.replace(/[^0-9\.]+/g, "");
          console.log("_"+str); 
      

      【讨论】:

        猜你喜欢
        • 2012-09-01
        • 2020-04-19
        • 2014-03-28
        • 1970-01-01
        • 2013-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-09
        相关资源
        最近更新 更多