将值在特定字符的第n个出现之后分割成不同的变量。

huangapple go评论71阅读模式
英文:

Split value into different variables, after a certain character nth

问题

const orignalValue = "BERNY564567JH89E"

const splitValueOne = orignalValue.substring(0, 11);
const splitValueTwo = orignalValue.substring(11);

英文:

Let's say I have this value 'BERNY564567JH89E'. How would I split the value into different strings, after the 11th character, which in this case would be 7. So for example, in the end I would have the following returned:

const orignalValue = "BERNY564567JH89E"

const splitValueOne = "BERNY564567"
const splitValueTwo = "JH89E"

答案1

得分: 1

你可以使用正则表达式匹配并限制计数使用 {11}

以下是使用 String.prototype.slice 的函数:

const
  orignalValue = 'BERNY564567JH89E',
  splitAtIndex = (str, index) => [str.slice(0, index), str.slice(index + 1)],
  [head, tail] = splitAtIndex(orignalValue, 11);

console.log({ head, tail }); // { "head": "BERNY564567", "tail": "JH89E" }

请注意,我只提供了代码的翻译部分。

英文:

You can match with a regex and limit your count using {11}.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const
  orignalValue = &#39;BERNY564567JH89E&#39;,
  [match, group1, group2] = orignalValue.match(/([a-z0-9]{11})([a-z0-9]*)/i) ?? [];

console.log({ group1, group2 }); // { &quot;group1&quot;: &quot;BERNY564567&quot;, &quot;group2&quot;: &quot;JH89E&quot; }

<!-- end snippet -->

Here is a function that uses String.prototype.slice:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const
  orignalValue = &#39;BERNY564567JH89E&#39;,
  splitAtIndex = (str, index) =&gt; [str.slice(0, index), str.slice(index + 1)],
  [head, tail] = splitAtIndex(orignalValue, 11);

console.log({ head, tail }); // { &quot;head&quot;: &quot;BERNY564567&quot;, &quot;tail&quot;: &quot;JH89E&quot; }

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月18日 03:44:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275682.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定