I have an array that I'm currently breaking down with the map function in order to only get the option index of the original array. This works, but now I'm wanting to strip this down and only get the first 2 numerical digits from that option index (or more specifically, anything in front of the '-' in that value)
What's the best way to strip out only those digits while mapping it the way I currently am?
var vm =
new Vue({
el: "#app",
data: {
options: [
{id:100, option:"1 - John Doe"},
{id:200, option:"2 - Jane Doe"}
]
},
methods: {
getNames(){
let names = this.options.map(option => {
return {
id: option.option
}
});
console.log(names);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="getNames()">TEST</button>
</div>
You can edit your map callback to get the first part of the string:
let options = [
{id:100, option:"1 - John Doe"},
{id:200, option:"2 - Jane Doe"}
];
let names = options.map(option => {
let opt = option.option;
id = opt.split(' - ')[0];
return { id };
});
console.log(names);
Pure JavaScript to Return only numbers from string.
Example for returned array:
[
{id: "1"},
{id: "2"}
]
Use replace with a regex to remove any non-numeric from the string - return only numbers (as string).
The regex is applied to all occurrences using the global flag behind surrounding slashes //g. The pattern inside slashes can be any of those equivalents to keep the numerical digits only:
\D matches all non-number characters (meta-character)[^0-9] matches all non-number characters (inversed character-range)Demo:
let options = [
{id:100, option:"1 - John Doe"},
{id:200, option:"2 - Jane Doe"}
];
// keep only the first digits before hyphen
let names = options.map(o => {
return {id: o.option.replace(/[^0-9]/g, "")};
});
console.log(names);
const names = this.options.map(option => {
const text = option.option // Get raw text from 'option'
const parts = text.split('-') // Split text string by the '-' (returns an array, E.g. ["1 ", " John Doe"])
return parts[0] // The first element of 'parts' is the result you are looking for (note it is a string, not a number)
})