英文:
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 = 'BERNY564567JH89E',
[match, group1, group2] = orignalValue.match(/([a-z0-9]{11})([a-z0-9]*)/i) ?? [];
console.log({ group1, group2 }); // { "group1": "BERNY564567", "group2": "JH89E" }
<!-- 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 = '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" }
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论