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]);
}
Related
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);
I have very long string that contains html as a string , numbers , my special bindings and numbers I want to split my bindings and sentences with spaces separately but my program is separately my bindings and words .
my js code:-
var x = 'hey this is {{name}} and I love to {{write}} and to learn as
much as I can. Now I am trying to separate sentences and my bindings'
var c = x.match(/\s*\S*\s*/g) // this splits words from string including
space
var mt = x.match(/{(.*)}/g); // trying to take out bindings but this don't
work
mt.forEach(function(a){ // taking each bindings separately
var z = x.match(a)
})
console.log(mt)
Somthing like this .. but I know this is totally wrong please help me
I don't have any idea :-
output that I am expecting:-
(5) ["hey this is", "i", "{{name}}", " and I love to ", "{{write}}", " and to learn as ↵ much as I can. Now I am trying to separate sentences and my bindings"]
How can i do this?
Please don't use jquery
Try this:
I've commented my code hoping it would make it easier to read. But do note that this code is far from perfect although it solves your problem.
var rawString = 'hey this is {{name}} and I love to {{write}} and to learn as much as I can. Now I am trying to separate sentences and my bindings';
var arrayRawString = rawString.match(/\s*\S*\s*/g); // this splits words from string including space
var arrayPlaceholder = rawString.match(/{(.\S*)}+/g); // trying to take out bindings but this don't work
// to store the final output
var separedArray = [];
// keeping track of the index to stich the array up
var posStart = 0;
var posEnd = 0;
arrayPlaceholder.forEach(function(arg){ // taking each bindings separately
// length of the array that holds placeholder (bindings)
var arsLength = arrayRawString.length;
for(var i = 0; i < arsLength; ++i) {
// if the provided text matches the original array's element
if(arrayRawString[i].match(arg)){
// to store the index
posEnd = arrayRawString.indexOf(arrayRawString[i]);
// join the pieces together upto the index defined
var res = arrayRawString.slice(posStart, posEnd).join('');
// to indicate whether the stored string is the placeholder
var flag = true;
// store the string obtained
separedArray.push(res.replace(arrayPlaceholder[(arrayPlaceholder.indexOf(arg) - 1) < 0 ? 0 : arrayPlaceholder.indexOf(arg) - 1 ], ''));
// check if the string still has placeholder (bindings)
// to remove it
for(var j = 0; j < arg.length; ++j) {
if(res[j] !== arg[j]) {
flag = !flag;
}
}
if ( flag ) {
separedArray.push(arg);
}
// last end position is the start position for next round
posStart = posEnd;
// because the loop runs only arrayPlaceholder.length times
// it solves the problem of last part not getting pushed to the final array
if( arrayPlaceholder[arrayPlaceholder.length-1] === arg ) {
res = arrayRawString.slice(posStart, arrayRawString.length).join('');
separedArray.push(res.replace(arg, ''));
}
}
}
});
console.log(separedArray);
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
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);
}
}
Lets say I have the following string:
var string = "<td>123</td><td>asd</td>";
I want to take the values of the td's and put them in an array. I tried using the foreach function but my regex stops after the first closing td and gets everything between < and >.
var regex = '<([^<> ]*)([^<>]*)?>([^>]*)<\/([^<>]*)>';
var string = "<td>123</td><td>asd</td>";
var result = string.match(regex);
result.forEach(function($var){
console.log($var);
});
Output:
<td>123</td>
td
undefined
123
td
I need to manipulate the values so I can work directly in the foreach function without first splitting to an array.
Can I make this work with a regex? I can't use jQuery or append the string to the html.
Using regex alone to parse DOM is a no-no. However..
If you don't have nested <td> you can use the following code to get an array of values:
var string = "<td>123</td><td>asd</td>";
var tds = string.split("</td>");
var values = [];
for(var i=0; i<tds.length-1; i++){ //last element is empty if you split like this
values.push(tds[i].substr(4)); //ommit the "<td>"
}
alert(values);
More complex structures could be a problem and I would advise you to break the TDs up to separate ones and then extract the values using regex (/<td>(.*)</td>/g and select group 1). But for this example it works fine.
jsFiddle
Split the string with any of <td> OR </td> and reject the "".
This will work for you
var string = "<td>123</td><td>asd</td>";
var contents = string.split(/<td>|<\/td>/);
contents = contents.filter(function(el){return el != ""})
console.log(contents) //["123","asd"]
Do not parse HTML using RegExp!
Here is a jQuery version for your problem:
$("<tr/>").append("<td>123</td><td>asd</td>") // build a row with the cells
.find("td") // get the cells
.map(function() { return $(this).text(); }); // for each cell, get the content
Result: ["123", "asd"]
Edit: I see you can't use jQuery, that's unfortunate because you really need a DOM parser, and jQuery is just elegant and can do much more.
You could try the below code,
> var re = /[^<>]+(?=<\/)/g;
undefined
> var result = string.match(re);
undefined
> result.forEach(function($var){
... console.log($var);
... });
123
asd
> console.log(result);
[ '123', 'asd' ]
Explanation:
[^<>]+ Matches any character not of < or > one or more times.
(?=<\/) Lookahead asserts that anything following must be </
Avoid parsing HTML/XML with regex!
I figured out a plain way with JavaScript to do it:
function extractValues(code)
{
var tr = document.createElement('tr');
tr.innerHTML = code;
var tds = values.getElementsByTagName('td');
var values = [];
for (var i = 0; i < tds.length; i++) {
values.push(tds[i].innerHTML);
}
return values;
}
console.log(extractValues("<td>123</td><td>asd</td>"));
If you realy realy want a regex, use this:
/<td>((?:.(?!<\/td>))*.?)<\/td>/g