I want split array value .
for example
gUser[1] = CAR.BENZ.CCLASS.1962
gUser[2] = CAR.PORSCHE.911.2001
I want get string only BENZ.CLASS.1962
and PORSCHE.911.2001
How to split array value on java script?
@update.
not always CAR
string. so, not use substring.
You can use map to access each string in array then use replace. Use a regex to match string before '.' and replace only the first match, like this:
var gUser = ['CAR.BENZ.CCLASS.1962', 'CAR.PORSCHE.911.2001']; var gUserModified = gUser.map(function(v){ return v.replace(/[^\\.]+\\./, ''); }); console.log(gUserModified);
Split it with dot then slice it and join it with dot
var gUser =[]; gUser[1] = "CAR.BENZ.CCLASS.1962"; gUser[2] = "CAR.PORSCHE.911.2001"; console.log(gUser[1].split('.').slice(1).join('.')); console.log(gUser[2].split('.').slice(1).join('.'));
From your question, it's not clear if the array is a string array
If it is a string array you can do:
ES6+: gUser.map((user)=>{return user.split("CAR.")[1]})
ES5: gUser.map(function(user){return user.split("CAR.")[1]});
The below code is not tested but should probably work, with maybe minor tweaks
var splitStr = '' var correctCarArr = [] for(let i = 0; i < gUser.length; i++){ splitStr = gUser[i].split('.') let temp = '' for(let j = 1; j < splitStr.length; j++){ temp += splitStr[j] } correctCarArr.push(temp) }
var gUser = []; gUser[1] = "CAR.BENZ.CCLASS.1962"; var gu1 = gUser[1].split("."); gu1.shift(); console.log(gu1.join("."));
Its easier split then shift the array to remove the first item like this:
gUser = ["CAR.BENZ.CCLASS.1962"]; var benz = gUser[0].split("."); benz.shift(); alert(benz.join('.'));
There are other options from shift like slice(1) but In terms of performance, shift is apparently faster https://jsperf.com/shift-pop-vs-slice/4
So here is the way without using any regex
by only using string and array methods.
const gUser = ['CAR.BENZ.CCLASS.1962', 'CAR.PORSCHE.911.2001', 'XYZAB.PORSCHE.YSA.2021'] for (let i = 0; i < gUser.length; i++) { console.log('Required String: ', gUser[i].split('.').slice(1).join('.')); }
What we do is, we split the string into parts where .
is encountered.
gUser[0].split('.')
returns ['CAR', 'BENZ', 'CCLASS', '1962']
Later when slice(1)
is called, the zeroth element of array is chopped off and will return ['BENZ', 'CCLASS', '1962']
And finally using join('.')
, we merge the array elements to a single string with a .
between each element, which returns BENZ.CCLASS.1962
Hope this helps! :)
Something Like This
`for(let index = 0; index < gUser.length; index++) {
console.log(gUser[index].split('.').splice(0, 1).join('.'));
}`
I haven't tested it. Please check and let me know
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.