remove specific text from variable - jquery - javascript

I have a variable in my script containing data test/test1. The part test/ is already stored in another variable. I want to remove test/ from the previous variable and want to store remaining part in another variable. how can I do this??
Thanks in advance...:)
blasteralfred

In your case, x/y:
var success = myString.split('/')[1]
You split the string by /, giving you ['x', 'y']. Then, you only need to target the second element (zero-indexed of course.)
Edit: For a more general case, "notWantedwanted":
var success = myString.replace(notWantedString, '');
Where notWantedString is equal to what you want to get rid of; in this particular case, "notWanted".

If your requirement is as straightforward as it sounds from your description, then this will do it:
var a = "test/test1";
var result = a.split("/")[1];
If your prefix is always the same (test/) and you want to just strip that, then:
var result = a.substring(5);
And if your prefix varies but is always terminated with a /, then:
var result = a.substring(a.indexOf("/") + 1);

To split at the first occurence of "/":
var oldstring = "test/test1";
var newstring = oldstring.substring(oldstring.indexOf("/")+1);
There are many other ways to do this, the other answers work fine too.

Have your pick:
JavaScript replace() function.
var data = "test/test1";
data = data.replace(/data/gi, 'test/');
Or:
var data = "test/test1";
var dataArray = data.split('/');
var data1 = dataArray[0];
var data2 = dataArray[1];

Related

How to split a string and make particular data only to be stored in a variable

I have a string like
var directoryPath = "file:///storage/sdcard0/Android/data/com.ionicframework.ftptranfer949961/cache/1467013143014.png"
in the above variable I would like storing only a particular string like this
var updatedPath = "/storage/sdcard0/Android/data/com.ionicframework.ftptranfer949961/cache/"
I have tried the split() method but I don't know how to store the particular path in my updatedPath variable.
What you could do is something like this:
var directoryPath = "file:///storage/sdcard0/Android/data/com.ionicframework.ftptranfer949961/cache/1467013143014.png";
var stringToReplace = 'file://';
var lastIndexOfSlash = directoryPath.lastIndexOf('/');
var offset = stringToReplace.length;
var updatedPath = directoryPath.substr(offset, lastIndexOfSlash - offset + 1);
alert(updatedPath);
This will set the updatePath variable to the directoryPath withouth the string you wish to remove (i.e. "file://") and remove the last part of the url where the .png location is set.

How to remove all characters before specific character in array data

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);
}
}

Replace different Values in String?

I have a string which looks like this: (id:561644cdb40fbe0100247dd7:q) (id:56165d8a79c8c40100adbdb6:q) and I need to replace the different id's with different values. I already have the id's in a variable and trying to loop through with something like this var mailId = "(id:" + rplcId + ":q)"; But If I use the replace() function it doesnt work...Any other suggestions?
You can select the id with:
"(id:56165d8a79c8c40100adbdb6:q)".split(":")[1]
var id = "(id:561644cdb40fbe0100247dd7:q)";
var idArr = id.split(":");
idArr[1] = newId; //56165d8a79c8c40100adbdb6
var mailId = idArr[0]+idArr[1]+idArr[2];
and please provide your full code

How to get the expression that matched with regexps

I'm trying to get the expression that matched in a regexp, it's not clear so there is some code for you to understand:
while (something) {
mymap[stmt.name] = {v : stmt.var}; //stmt.name is changing on each loop
regexpString += stmt.name+"(.*)|";
}
regexpString = regexpString.slice(0, -1);
regexpE = new RegExp(regexpString, "i");
test = regexpE.exec(somevar);
Now, I want to get the stmt.name that match in order to get the element in the map, with mymap[test] or something like that.
Is there a way through it, or a better way that I didn't see ? I don't want to loop on each stmt.name each time, it will be heavy this way.
if my regexpString equals http://foo.bar(.*)|https://bar.foo/foobar/(.*) I want to be able to get http://foo.bar or https://bar.foo/foobar/ according to my somevar variable
Why not just capture it? Use
var names = [];
while (something) {
mymap[stmt.name] = {v : stmt.var}; //stmt.name is changing on each loop
names.push(stmt.name);
}
var regexpE = new RegExp("("+names.join("|")+")(.*)", "i");
var test = regexpE.exec(somevar);
var name = test[1],
_var = mymap[name].v;

Split function going Abnormal in JavaScript

This is the Contents of file from where i am reading...
aaa 3333,bbb 5,ccc 10
I am getting un defined for the keyvalue[2], [3], [4] and [5]. Why is it so???
I am actually first spliting based on , and then based on space.
because you split by comma first, so item is now 'PrimeSuiteId 3333'. When you split that by space you get two items only, so 3rd value (keyvalue[2]) and above is empty.
Edit: possible fix to make second part of your script work
swap
var items = contents.toString().split(',');
with
var items = contents.toString().replace(/,/,' ');
which will simply replace commas with spaces in the original string so your array of expected values matches up
Another edit: because splitting by comma or space is better (as in comments)
var contents = f.read();
Ti.API.info(contents);
var items = contents.toString(); // changed to return complete string not split
// removed for loop altogether
var keyvalue = items.split(/,|\s/); // changed to split by comma or space
var AppointmentSearchDaysAfter = keyvalue[0];
var AppointmentSearchDaysAfterValue = keyvalue[1];
var AppointmentSearchDaysBefore = keyvalue[2];
var AppointmentSearchDaysBeforeValue = keyvalue[3];
var PrimeSuiteId = keyvalue[4];
var PrimeSuiteIdValue = keyvalue[5];
From the contents in the contents file you should only be able to get values for
var AppointmentSearchDaysAfter = keyvalue[0];
var AppointmentSearchDaysAfterValue = keyvalue[1];
You only have one space for each data entry between the commas
Split function is working fine, you are expecting it to behave abnormal.
You will get only two values in array after split by space. From where will it bring 6 values!!!?
The rest values you will get in next iterations.
Instead of declaring individual variables for each item and then loading them from the contents string, you can reduce the whole thing to an object with key/value pairs:
var items = contents.split(',').reduce(function (acc, val) {
var split = val.split(' ');
return acc[split[0]] = split[1], acc;
}, {});
To test what the values are, try:
console.log(items.PrimeSuiteId); // outputs 3333
console.log(items.AppointmentSearchDaysBefore); // outputs 5
console.log(items.AppointmentSearchDaysAfter); // outputs 10

Categories

Resources