So, I have a string with the delimiter | , one of the sections contains "123", is there a way to find this section and print the contents?
something like PHP explode (but Javascript) and then a loop to find '123' maybe? :/
const string = "123|34|23|2342|234";
const arr = string.split('|');
for(let i in arr){
if(arr[i] == 123) alert(arr[i]);
}
Or:
for(let i in arr){
if(arr[i].indexOf('123') > -1) alert(arr[i]);
}
Or:
arr.forEach((el, i, arr) => if(arr[i].indexOf('123') > -1) alert(arr[i]) }
Or:
arr.forEach((el, i, arr) => if(el == '123') alert(arr[i]) }
Or:
const arr = "123|34|23|2342|234".split('|')
if(arr.some(el=>el == "123")) alert('123')
More information on string and Array memeber functions.
You can use split() in JavaScript:
var txt = "123|1203|3123|1223|1523|1243|123",
list = txt.split("|");
console.log(list);
for(var i=0; i<list.length; i++){
(list[i]==123) && (console.log("Found: "+i)); //This gets its place
}
LIVE DEMO: http://jsfiddle.net/DerekL/LQRRB/
This should do it:
var myString = "asd|3t6|2gj|123hhh", splitted = myString.split("|"), i;
for(i = 0; i < splitted.length; i++){ // You could use the 'in' operator, too
if(splitted[i].match("123")){
// Do something
alert(splitted[i]); // Alerts the entire contents between the original |'s
// In this case, it will alert "123hhh".
}
}
.split is the equivalent of explode, whereas .join is the equivalent of implode.
var myString = 'red,green,blue';
var myArray = myString.split(','); //explode
var section = myArray[1];
var myString2 = myArray.join(';'); //implode
Related
I have an below string with two delimeter."|" is used for rows and "*" is used for columns.I would like to know how to split these string by rows and column in JS Code
"1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|"
You could use the split function twice to create nested array:
let str = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|";
let arr = str.split("|").map(r => r.split("*"));
console.log(arr);
You can split with multiple delemiter with.
const str = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|"
const splitStr = str.split(/\*|\|/);
console.log(splitStr);
const input = "1264.75|24936.00|38230.76|48329.75|53106.25|63442.00|75122.50|1077.00|117581.00|127573.25|133509.00|215246.50|244181.00|254961.25|52*34.00|"
// The filter is for removing empty rows
input.split("|").filter(val=>!!val).map(val => val.split("*").map(res=>parseFloat(res)))
The result will be like
[[1264.75],[24936],[38230.76],[48329.75],[53106.25],[63442],[75122.5],[1077],[117581],[127573.25],[133509],[215246.5],[244181],[254961.25],[52,34]]
Plenty of good answers here already - this returns as an array of cell objects with row/column attributes:
let mystring = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|";
let cells = mystring.split("|");
let results = [];
for (let i = 0; i < cells.length; i++) {
let cell = cells[i];
let cellData = cell.split("*");
results.push({
row: cellData[0],
col: cellData[1]
})
}
console.log(results);
If you want to go over it in one pass, this should create a nested array structure representing arrays / columns. It is also very rough and can likely be simplified a bit.
const fullStr = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|";
const arr = [[]];
for(let i = 0, str = ''; i < fullStr.length; i++){
if(fullStr[i] == '*') {
arr[arr.length - 1].push(str);
str = '';
continue;
}
if(fullStr[i] == '|') {
arr[arr.length -1].push(str);
// you could wrap this push statement in an if to determine if you are at the end of the string.
arr.push([]);
str = '';
continue;
}
str += fullStr[i];
}
console.log(arr);
Maybe a little old-fashioned but works just as well
var a ="1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00";
var b = a.split("|");
var c = [];
for (i = 0; i < b.length; i++) {
c[i] = b[i].split("*");
}
I have one array and I store comma separated strings in the array. Now I want to take in the string every first letter take from the string with comma separated.
For ex => Abc, Xyz, Hji so now I want A, X, H.
Here below listed my code and array.
This is my code =>
var ArryString = [];
for (var i = 0; i < data.length; i++) {
ArryString.push(data[i].Str);
}
Current o/p =>
"Abc"
"Xyz,Hji,Lol",
"Uyi,Mno"
my expacted o/p= >
"A"
"X,H,L"
"U,M"
You could split the strings and take only the first character with a destructuring assignment and join the first characters for a string. Then map the new string for a new array.
var data = ["Abc", "Xyz,Hji,Lol", "Uyi,Mno"];
result = data.map(s => s
.split(',')
.map(([c]) => c)
.join());
console.log(result);
This is not looking good and amateurish but understandable.
var ArryString = [];
var data = ["Abc", "Xyz,Hji,Lol", "Uyi,Mno"];
var index=0;
for (var k in data){
var a=data[k].split(",");
ArryString[index]=a[0].charAt(0);
if(a.length > 1)
for (var l=1 ;l<a.length ; l++)
ArryString[index]+=","+a[l].charAt(0);
index++;
}
console.log(ArryString);
You can use charAt method Return the first character of a string.
var newString = [];
for (var i=0; i< newString.length; i++)
{
newString.push(ArrayString[i].charAt(0);
}
Here is a working example :
// We've got an array of comma separated worlds
// Sometimes we've got one, sometimes several
data=["Hello","i","have","one,array","and,i","store","comma,separated,string,in","the","array"];
// We want to ouput the same pattern but keeping the initial letter only
var result = [];
var items = [];
var aChar;
// We loop thru the data array
for (var i = 0; i < data.length; i++) {
// We make a small array with the content of each cell
items = data[i].split(",");
for (var j = 0; j < items.length; j++) { // We loop thru the items array
aChar = items[j].charAt(0); // We take the first letter only
if (aChar!="") // If the item/work was not empty the we keep only the initial letter in our items array
items[j] = aChar;
}
result.push(items.join(",")); // we store comma separated first letters in our result array
}
console.log(result)
Use the String.charAt() method for each string in the array and push the first character to a new array.
Example function:-
function takeFirstChar(arr){
var new_arr = [];
arr.forEach(function(el){
var firstLetter = el.charAt(0)
new_arr.push(firstLetter);
});
return new_arr;
}
takeFirstChar(['hello','cruel','world']);
//Output-> ['h','c','w']
I'm trying to create an array of strings and produce the possibilities by the length of array string. For example:
var someStr = ["a","b","c","d"];
//I want to produce this outcome
a
ab
abc
abcd
b
bc
bcd
c
cd
d
I know I can get the # of possibilities for "a" only by this way:
var numCombinations = 0;
var comboString = '';
var outcome = [];
for(var i = 0; i < someStr.length; i++){
comboString += someStr[i];
outcome[i] = comboString;
numCombinations += i; //# of combinations from above
}
But how would I continue with these variables for the left over possibilities? I've thought of creating nested for-loops again and again but that would eventually lead to the (n)th length with hard-coding. Would there be any method(s) to create this and store all the possibilities to the (n)th length?
Hope this help.
function getComboStringListFromIdx(arr, idx){
var result = [];
var comboString = '';
for(var i=idx; i<arr.length; i++){
comboString += arr[i];
result.push(comboString);
}
return result;
}
var someStr = ['a','b','c','d'];
var outCome = [];
for(var i = 0; i<someStr.length; i++){
outCome = outCome.concat(getComboStringListFromIdx(someStr, i));
}
I will also use nested for-loop ! One is normal looping and other is to skip less than current index from first loop !!
var someStr = ["a","b","c","d"];
for(var i = 0;i < someStr.length;i++) {
output(i);
}
function output(index) {
var str = "";
for(var j in someStr) {
if(j < index) {
continue;
}
str += someStr[j];
console.log(str);
}
}
This solution uses a nested for loop and skips concatenation on the first element of the nested for loop.
var arr = ["a","b","c","d"];
for(var i=0;i<arr.length;i++){
var str = arr[i];
for(var j=i;j<arr.length;j++){
if(i!==j)
str+=arr[j];
console.log(str);
}
}
https://jsfiddle.net/fmy539tj/
If my string looks like this
"<First key="ab" value="qwerty"/>
<First key="cd" value="asdfg"/>
<First key="ef" value="zxcvb"/>"
and I want to get data out in the format
ab:"qwerty"
cd:"asdfg"
ef:"zxcvb"
How should I write the JS ?
It would be useful to see the code you've attempted, but here's a way you could achieve it:
Use a regex to pick out the relevant parts of the string.
var regex = /key="([a-zA-Z]+)" value="([0-9a-zA-Z\-\.]+)"/;
Function to remove empty elements.
var notEmpty = function (el) { return el !== ''; };
split the string into an array on the carriage return and use reduce to build the new object by applying the regex to each array element.
var out = str.split('\n').filter(notEmpty).reduce(function(p, c) {
var match = c.match(regex);
p[match[1]] = match[2];
return p;
}, {});
OUTPUT
{
"ab": "qwerty",
"cd": "asdfg",
"ef": "zxcvb"
}
DEMO
Please, make your question more clear(What result data type would you like to get?), or try these functions:
var string = '<First key="ab" value="qwerty"/><First key="cd" value="asdfg"/><First key="ef" value="zxcvb"/>'
var ParseMyString1 = function(str){
var arr = str.split(/[</>]+/); //"
//console.log(arr);
var result = [];
for (var i =0; i<arr.length; i++) {
var subStr=arr[i];
if (subStr.length!==0) {
var subArr = subStr.split(/[\s"=]+/); //"
//console.log(subArr);
var currObj = {};
var currKey = "";
var currVal = "";
for (var j =0; j<arr.length; j++) {
if (subArr[j]=="key"){
currKey = subArr[++j];
}else if (subArr[j]=="value"){
currVal = subArr[++j];
}
};
currObj[currKey] = currVal;
result.push(currObj);
};
};
console.log("ParseMyString1:");
console.log(result);
};
var ParseMyString2 = function(str){
var arr = str.split(/[</>]+/); //"
//console.log(arr);
var resultObj = {};
for (var i =0; i<arr.length; i++) {
var subStr=arr[i];
if (subStr.length!==0) {
var subArr = subStr.split(/[\s"=]+/); //"
//console.log(subArr);
var currKey = "";
var currVal = "";
for (var j =0; j<arr.length; j++) {
if (subArr[j]=="key"){
currKey = subArr[++j];
}else if (subArr[j]=="value"){
currVal = subArr[++j];
}
};
resultObj[currKey] = currVal;
};
};
console.log("ParseMyString2:");
console.log(resultObj);
};
$(document).ready(function(){
ParseMyString1(string);
ParseMyString2(string);
});
These functions return results as below (array of objects):
ParseMyString1:
[{ab:"qwerty"},{cd:"asdfg"},{ef:"zxcvb"}]
ParseMyString2:
{ab:"qwerty",cd:"asdfg",ef:"zxcvb"}
First, your string is not valid (double quotes within double quotes). You'd either need to escape the inner quotes with \" or just replace the inner quotes with single quotes.
But, assuming that your data was always going to be in the format you show, this simple code will extract the data the way you want:
var data = "<First key='ab' value='qwerty'/><First key='cd' value='asdfg'/><First key='ef' value='zxcvb'/>";
data = data.replace(/<First /g, " ").replace(/\/>/g, "").replace(/key=/g, "").replace(/value=/g, "").trim();
var ary = data.split(" ");
var iteration = "";
var result = "";
for(var i = 0; i < ary.length; i+=2){
iteration = ary[i].replace(/'/g, "") + ":" + ary[i+1].replace(/'/g, "\"");
alert(iteration);
result += " " + iteration;
}
alert("Final result: " + result);
Your input is a kind of XML. The best way is to treat it as such. We will parse it as XML, but to do so, we need to first wrap it in a root element:
var str = "<Root>" + input + "</Root>"
We parse it with
var parser = new DOMParser();
var dom = parser.parseFromString(str, "text/xml");
Get the document element (Root):
var docelt = dom.documentElement;
Now we can loop over its children and build our result, using standard DOM access interfaces like getAttribute:
var result = {};
var children = docelt.children;
for (var i = 0; i < children.length; i++) {
var child = children[i];
result[child.getAttribute('key')] = child.getAttribute('value');
}
> result
< Object {ab: "qwerty", cd: "asdfg", ef: "zxcvb"}
You can replace the above looping logic with reduce or something else as you prefer.
This approach has the advantage that it takes advantage of the built-in parser, so we don't end up making assumptions about the syntax of XML. For instance, the regexp suggested in another answer would fail if the attributes had spaces before or after the equal sign. It would fail if the values contained Unicode characters. It would fail in odd ways if the XML was malformed. And so on.
I have an array that contains string.
var js_userBoxName = new Array();
I want to search the elements of the array if a string has the word "foo" it should displayed.
So for example my array contains the words {foofy, foofa, foo, awtsy}, foofy, foofa and foo will be displayed since they all contains the word foo.
Check out the Array.filter method:
var arr = ['foofy', 'foofa', 'foo', 'awtsy'];
var fooItems = arr.filter(function (item) {
return item.indexOf('foo') >= 0;
});
// Yields ['foofy', 'foofa', 'foo']
The linked MDN page contains a polyfill for browsers that do not support it. If you happen to be using jQuery, you could use $.grep:
var arr = ['foofy', 'foofa', 'foo', 'awtsy'];
var fooItems = $.grep(arr, function (item) {
return item.indexOf('foo') >= 0;
});
You could also try this:
var myarray = ["foofy", "foofa", "foo", "awtsy"];
var searched_string = "foo";
var foundmatch = [];
for(i=0; i < myarray.length; i++){
if(myarray[i].match(searched_string)){
foundmatch.push(myarray[i]);
}
}
alert(foundmatch);
NOTE: Good performance tip is to always cache the length of your array when iterating over it rather than recalculating it for each loop execution. len = js_userBoxName.length
http://jsperf.com/caching-array-length/4
function () {
for(var i = 0, len = js_userBoxName.length; i < len; i++){
if(typeof js_userBoxName[i] === 'string'){
if(js_userBoxName[i].indexOf('foo') == -1)
return true;
}
}
return false;
}
The following function should do the trick, it uses only standard acme script elements
function Find (myarray, searchterm){
for (var i=0, len = myarray.length; i<len; i += 1){
if (typeof(myarray[i]) === 'string' && myarray[i].search(searchterm) !== -1){
// print or whatever
//hint use a callback here that you pass in as an additional arugment
}
}
}
using search allows you to use regex if you need to check for something more complex
The following should work:
var myArray = ['foofy', 'foofa', 'foo', 'awtsy'];
for ( var i = 0; i < myArray.length; i++ ) {
if ( myArray[i].contains('foo') )
console.log(myArray[i]);
}
prints:
foofy
foofa
foo
Note: "awtsy" does not contain the pattern foo