How to remove all characters before specific character in array data - javascript

I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.
I created a simple work-in-progress JSFiddle: https://jsfiddle.net/2Lfo4966/
The string I receive is the following:
ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC
ABCD/ in the string above can change, and may be XYZ, MNO, etc.
To convert to an array, I've done the following:
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
Using console.log, I get the following result:
["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]
I'm now at the point where I need the code to look at each index of array, and if / exists, remove all characters before / including /.
I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.

You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:
for (var i = 0; i < currentUserRole.length; i++) {
var data = currentUserRole[i].split('/');
currentUserRole[i] = data.pop();
}
Example fiddle
The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.
You could go one step further and make this more succinct by using map():
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',').map(function(user) {
return user.split('/').pop();
});
console.log(currentUserRole);

You can loop through the array and perform this string replace:
currentUserRole.forEach(function (role) {
role = role.replace(/(.*\/)/g, '');
});

$(document).ready(function(){
var A=['ABCD','ABCD/Admin','ABCD/DataManagement','ABCD/XYZTeam','ABCD/DriverUsers','ABCD/RISC'];
$.each(A,function(i,v){
if(v.indexOf('/')){
var e=v.split('/');
A[i]=e[e.length-1];
}
})
console.log(A);
});

You could replace the unwanted parts.
var array = ["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"];
array = array.map(function (a) {
return a.replace(/^.*\//, '');
});
console.log(array);

var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(i=0;i<currentUserRole.length;i++ ){
result = currentUserRole[i].split('/');
if(result[1]){
console.log(result[1]+'-'+i);
}
else{
console.log(result[0]+'-'+i);
}
}
In console, you will get required result and array index

I would do like this;
var iur = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC',
arr = iur.split(",").map(s => s.split("/").pop());
console.log(arr);

You can use the split method as you all ready know string split method and then use the pop method that will remove the last index of the array and return the value remove pop method
var importUserRole = ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++;){
var data = currentUserRole[x].split('/');
currentUserRole[x] = data.pop();
}
Here is a long way
You can iterate the array as you have done then check if includes the caracter '/' you will take the indexOf and substact the string after the '/'
substring method in javaScript
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++){
if(currentUserRole[x].includes('/')){
var lastIndex = currentUserRole[x].indexOf('/');
currentUserRole[x] = currentUserRole[x].substr(lastIndex+1);
}
}

Related

Array not giving expected answer using split function

In this code console.log (name[i]) results in first character of split string(i.e. c ,s,t) but i want name separate like chris. and its giving the expected result on MDN but not on console on js.
var char=['chris:2255655','sarrah:5456454','taur:5655226'];
var name=new Array();
for(var i=0;i<char.length;++i){
name=char[i].split(':');
console.log(name[i]);
}
Your code should look like
var char=['chris:2255655','sarrah:5456454','taur:5655226'];
for(var i=0;i<char.length;++i){
var w = char[i].split(":");
console.log(w[0]);
}
Please check my snippet. It seems that your split was not resulting an array but a string. So you were getting only the first symbol
You can simply do:
var char=['chris:2255655','sarrah:5456454','taur:5655226']
// As array
console.log(char.map(x => x.split(':')[0]))
// As a string
console.log(...char.map(x => x.split(':')[0]))
We are using map to go through each of the strings and split on :.
Since split gives us an array we take the 0 index which contains the name. Since Map returns an array you can either leave as is or destructure it with ... to get its contents.
You can do like this.
const char=['chris:2255655','sarrah:5456454','taur:5655226'];
const name= [];
for(let i=0;i<char.length;i++){
let val =char[i].split(':');
name.push(val[0]);
console.log(name[i]);
}
Since you know the position of your selection you can assign directly to a variable:
var char = ['chris:2255655', 'sarrah:5456454', 'taur:5655226']
var names = char.map(item => {
var [name] = item.split(':'); // <- select only first index
// var [name, id] = item.split(':'); // <- select first and second index
// var [name, ...rest] = item.split(':'); // <- select first and rest of the elements
// var [name,] = item.split(':'); // <- select first and skip next element index using ","
return name;
})
console.log(names);

How to remove a part of all strings in an array in javascript?

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("."));
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! :)
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
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

how to split the textarea into parts in javascript

I am trying to open the 5 urls inputted by the user in the textarea
But the array is not taking the url separately instead taking them altogether:
function loadUrls()
{
var myurl=new Array();
for(var i=0;i<5;i++)
{
myurl[i] = document.getElementById("urls").value.split('\n');
window.open(myurl[i]);
}
}
You only should need to split the text contents once. Then iterate over each item in that array. I think what you want is:
function loadUrls() {
var myurls = document.getElementById("urls").value.split('\n');
for(var i=0; i<myurls.length; i++) {
window.open(myurls[i]);
}
}
Here's a working example:
var input = document.getElementById('urls');
var button = document.getElementById('open');
button.addEventListener('click', function() {
var urls = input.value.split('\n');
urls.forEach(function(url){
window.open(url);
});
});
<button id="open">Open URLs</button>
<textarea id="urls"></textarea>
Note that nowadays browsers take extra steps to block popups. Look into developer console for errors.
There are a couple issues I see with this.
You are declaring a new Array and then adding values by iterating through 5 times. What happens if they put in more than 5? Or less?
split returns a list already of the split items. So if you have a String: this is a test, and split it by spaces it will return: [this, is, a, test]. There for you don't need to split the items and manually add them to a new list.
I would suggest doing something like:
var myUrls = document.getElementById("urls").value.split('\n');
for (var i = 0; i < myUrls.length; i++) {
window.open(myUrls[i]);
}
However, as others suggested, why not just use multiple inputs instead of a text area? It would be easier to work with and probably be more user friendly.
Basically:
document.getElementById("urls").value.split('\n');
returns an array with each line from textarea. To get the first line you must declare [0] after split the function because it will return the first item in Array, as split will be returning an Array with each line from textarea.
document.getElementById("urls").value.split('\n')[0];
Your function could simplify to:
function loadUrls(){
var MyURL = document.getElementById("urls").value.split('\n');//The lines
for(var i=0, Length = MyURL.length; Length > i; i++)
//Loop from 0 to length of URLs
window.open(
MyURL[i]//Open URL in array by current loop position (i)
)
}
Example:
line_1...
line_2...
... To:
["line_1","line_2"]

How to get string in regular expression with space

This is my input as string
'controls: ["aa.bb.cc","dd.ee.ff"],elements: []'
I want to get the result of the data in the controls meaning :
"aa.bb.cc","dd.ee.ff"
I tried pattern
/.*(controls:.*).*/
but I didn't get all the result
I think my problem is becuase the new line
You can do it with regEx
var c = 'controls: ["aa.bb.cc", "dd.ee.ff"], elements: []';
var match = c.match(/("[a-z.]+")/g);
// or c.match(/([a-z][a-z][.][a-z][a-z][.][a-z][a-z])/);
// to strictly match letters . letters . letters
// or for a shorter match: c.match(/(\w+[.]\w+[.]\w+)/);
console.log(match); // an array of your values
EDIT:
if you only want to get the values in controls and not element, you can get the controls values out with the regEx /controls: ([\["a-z., \]]+,)/g
You could simply parse your input as a JSON object then loop throught the controls array:
var input='controls: ["aa.bb.cc", "dd.ee.ff"],
elements: []';
json = JSON.parse(input);
var controls=json.controls;
//then loop throught the controls values
for(var i=0;i<controls.length;i++){
console.log(controls[i]);
}
I think that should do it.
This might look like a very crude solution, but it works.
This expression will give you aa.bb.cc :
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[1]
and this will give the next element i.e. dd.ee.ff
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[2]
In general,
var str = "controls: [\"aa.bb.cc\",\"dd.ee.ff\"],elements: []";
var resLength = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/).length;
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/);
for (var i=1; i<resLength; i++) {
console.log(res[i]);
}

Remove items from based of substring in array jquery

This might seems a very newbie sort of question, but I am struggling with this as of now and seek some help.
Here is a example array in JavaScript
var SelectedFilters = ["[size:12:12]","[size:12:12]","[size:13:13]","[size:14:14]", "[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
Now I wish to remove certain items from this array based on a search term, now the search term contains only a part of string such as
var searchTerm1 = 'size'
var searchTerm2 = 'color'
I have already tried the following code, but its not working:
var i = SelectedFilters.indexOf(searchTerm1);
if (i != -1)
{
SelectedFilters.splice(i, 1);
}
I have also tried running to through for loop, to iterate on all items, but again search failed as its not able to match 'size' OR 'color'
What I am looking: if searchterm1 is used, the resulted output will be like:
["[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
and in case of searchterm2 is used the resulted output should be:
["[size:12:12]","[size:12:12]","[size:13:13]","[size:14:14]","[type:14:14]","[type:14:14]"];
It would be great if anyone can solve this puzzle, I am also trying to find a solution in the meantime.
Your attempt didn't work because .indexOf() on an Array looks for an exact match.
Since according to your question and comment you need to mutate the original Array, you should loop over the array and test each string individually and then call .splice() every time you find one that needs to be removed.
var SelectedFilters = ["[size:12:12]","[size:12:12]","[size:13:13]","[size:14:14]", "[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
var searchTerm1 = 'size'
var searchTerm2 = 'color'
for (var i = SelectedFilters.length-1; i > -1; i--) {
if (SelectedFilters[i].startsWith(searchTerm1, 1)) {
SelectedFilters.splice(i, 1)
}
}
document.querySelector("pre").textContent =
JSON.stringify(SelectedFilters, null, 2)
<pre></pre>
The loop used above goes in reverse. This is important since every time we do a .splice(), the array gets reindexed, so if we went forward, we would end up skipping over adjacent items to be removed.
The .startsWith() method checks if the string starts with the given search term. I passed the second parameter a value of 1 so that it starts searching on the second character.
You can use filter method of array
var searchTerm = "size";
SelectedFilters = SelectedFilters.filter(function(val){
return val.indexOf( searchTerm ) == -1;
});
You can do it with Array#filter,
var searchTerm1 = 'size';
var result = SelectedFilters.filter(v => !v.includes(searchTerm1));
console.log(result); //["[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
If you want to alter the original array then do,
var SelectedFilters = ["[size:12:12]", "[size:12:12]", "[size:13:13]", "[size:14:14]", "[color:14:14]", "[color:14:14]", "[type:14:14]", "[type:14:14]"];
var searchTerm1 = 'size',cnt = 0, len = SelectedFilters.length - 1;
while (cnt <= len) {
if (SelectedFilters[len - cnt].includes(searchTerm1)) SelectedFilters.splice(len - cnt, 1);
cnt++;
}
console.log(SelectedFilters);
DEMO

Categories

Resources