Convert array to space-delimited string, while joining individual values - javascript

I have a multiple select box on my page. I can get the values of all the selected child options in jQuery easily like this:
$("#select").val();
That gives me an array like this:
["Hello", "Test", "Multiple Words"]
Now, I want to convert this array into a space-delimited string, but also join the individual words in each value with a dash, so that I end up with this:
"Hello Test Multiple-Words"
How would I go about doing that?

var values = $("#select").val();
for (var i = 0; i < values.length; ++i) {
values[i] = values[i].replace(" ", "-");
}
var spaceDelimitedString = values.join(" ");

var result = $.map($("#select").val() || [], function (x) {
return x.replace(/\s/g, '-');
}).join(' ');

If Multiple-Words can be as Multiple Words, then you can simply use .join and get the final output as "Hello Test Multiple Words".
If not, you can write a loop like below to get the result.
var myList = ["Hello", "Test", "Multiple Words"];
var result = '';
for (var i = 0; i < myList.length; i++) {
result += myList[i].replace(/\s/g, '-') + ' ';
}
DEMO: http://jsfiddle.net/bmXk5/

Here a simple one liner with Array.map:
var arr = ["Hello", "Test", "Multiple Words"];
arr.map(function(val) { return val.replace(' ', '-') }).join(' ');

var vals = ["Hello", "Test", "Multiple Words"];
var result = $.map(vals, function(str){ return str.replace(/\s/g, '-') })
.join(' ');

This should do the job for you.
function combineWords(arr) {
var i, l;
for(i = 0, l = arr.length; i < l; i++) {
arr[i] = arr[i].replace(' ', '-') ;
}
return arr;
}

Related

How to join an array of strings without using .join()?

We're trying to write a function that takes an array of strings and a separator, and joins all the strings separated by such separator.
We are not allowed to use the .join() method.
So far, I'm stuck trying to iterate though all the strings adding a separator between them each time.
I tried something like:
var aName = ['Frank','Vincent','Zappa'];
var join = (arr, separator = " ") => {
for(var i = 0; i < arr.length; i++) {
return arr[i] + separator + arr[i+1];
}
};
join(aName, ' ');
//output: "Frank Vincent"
//expected output: "Frank Vincent Zappa"
Thanks for your help.
You can reduce the array:
function join(arr, separator)
{
return arr.reduce((str, a)=> {return a+separator+str})
}
To fix your current code, try concatenating instead, and return only at the end:
var aName = ['Frank', 'Vincent', 'Zappa'];
var join = (arr, separator = " ") => {
let result = '';
for (var i = 0; i < arr.length; i++) {
if (result) {
result += separator;
}
result += arr[i];
}
return result;
};
console.log(join(aName, ' '));
A very simple method is to append the separator only for the second element onwards:
const arr = ["Frank", "Vincent", "Zappa"];
const join = (arr, sep = " ") => {
if (!arr || !arr.length) return "";
let ret = arr[0];
for (let i = 1; i < arr.length; i++) {
ret += sep + arr[i];
}
return ret;
};
console.log(join(arr));
console.log(join(arr, "-"));
You can use the String constructor
var name = ['Frank', 'Vincent', 'Zappa'];
console.log(String(name).replace(/,/g,' '))
You could check the length of the array first and return an empty string if length is zero.
Otherwise take the first element as start value for the result and iterate from the second element and add the separator and the value of the array.
Proceed until no more elements. Then return the result string.
var join = (array, separator = ' ') => {
if (!array.length) return '';
var result = array[0];
for (var i = 1; i < array.length; i++) {
result += separator + array[i];
}
return result;
},
array = ['Frank', 'Vincent', 'Zappa'];
console.log(join(array, ' '));
The problem with your code is that you use return in a for loop which means that function will stop it's execution and return a value you write in return.
To avoid that you should write something like this:
var name = ['Frank','Vincent','Zappa'];
var join = (arr, separator = " ") => {
var result = '';
for(var i = 0; i < arr.length; i++) {
// adding to result string arr[i] and separator
result += arr[i] + separator;
}
// deleting separator in the end of string
return result.slice(0, -1);
};
join(name, ' ');
To be precise it is not possible to create a string without join() since JavaScript will internally always call join() for arrays. But if you just want to create your own join() function you can iterate through the array, add a separator to your current item and do this until you reached the end where you only add your current item without a separator.
var name = ['Frank', 'Vincent', 'Zappa'];
function join(arr, separator = " ") {
var str = "";
if (arr.length === 0) return str;
for (var i = 0; i < arr.length; i++) {
str += i !== arr.length - 1 ?
arr[i] + separator :
arr[i];
}
return str;
};
console.log(join(name, ' '));
A solution using a curried function in es2015
const joinStrings = glue = ' ' => strings => {
let res = '';
strings.forEach(str => res += glue + str);
return res.replace(glue, '');
}
const joined = joinStrings(', ')(['a', 'b', 'c']);
console.log(joined);
var names = ['Frank','Vincent','Zappa'];
const join = (names, separator) => {
let str = '';
for(let i = 0; i < names.length; i++) {
str += (str ? separator : '') + names[i];
}
return str;
}
console.log(join(names, ' '));
function joinFunction(arr){
let string = ''
for( let char of arr ){
string += char + ' '
}
console.log(string)
}
joinFunction(['Frank','Vincent','Zappa'])

How to clean , from a given string?

I have data like this.
var abc =",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
abc = abc.split(",");
let stub={};
var results=[];
var key=["name","value","acc"];
var i=0;
var j=0;
for( var i = 0 ; i <abc.length - 1;i++){
stub[key[j]=abc[i];
j++
if(j==3){
results.push(stub);
stub={};
j=0;
}
}
abc = results;
I would like to get those values arranges in form of array of object having those 3 keys:
output should be:
abc = [{"name": "paul", "value": "2000","acc":"12sc21"},{"name":"logan","value":"123","acc":"21sdf34"},{"name":"vfsarwe","value":"456456","acc":"32fd23"}];
but not able to get the desired output. this output only comes when string don't have ,,,,,, in starting. But the data i'm getting is sometimes having ,,,,, in stating.
You can use abc.replace(/(^[,\s]+)/g, '') to remove leading commas or whitespace from the String. Your for loop is also not running for long enough; it is looping until there is only one element left in the Array and then stopping.
Change
for(var i = 0 ; i < abc.length-1; i++)
To
for(var i = 0 ; i < abc.length; i++)
var abc =",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
abc = abc.replace(/(^[,\s]+)|([,\s]+$)/g, '').split(",");
let stub={};
var results=[];
var key=["name","value","acc"];
var i=0;
var j=0;
for(var i = 0 ; i < abc.length; i++){
stub[key[j]]=abc[i];
j++
if(j==3){
results.push(stub);
stub={};
j=0;
}
}
abc = results;
console.log(abc);
You can use .replace(/^\,+/, '') to remove all leading commas, then split by comma to get an array, then loop over this array using 3 as step and construct your results:
var abc = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var arr = abc.replace(/^\,+/, '').split(",");
var results = [];
for (var i = 0; i < arr.length; i = i + 3) {
results.push({
"name": arr[i],
"value": arr[i + 1],
"acc": arr[i + 2]
});
}
Demo:
var abc = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var arr = abc.replace(/^\,+/, '').split(",");
var results = [];
for (var i = 0; i < arr.length; i = i + 3) {
results.push({
"name": arr[i],
"value": arr[i + 1],
"acc": arr[i + 2]
});
}
console.log(results);
You are on the right track with splitting your data on ,. You can then split the data in to chunks of 3, and from there map each chunk to a dict.
var data = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var split = data.split(",");
var chunked = [];
while (split.length) {
chunked.push(split.splice(0,3));
}
var res = chunked.map((i) => {
if (!i[0] || !i[1] || !i[2]) {
return null;
}
return {
name: i[0],
value: i[1],
acc: i[2]
};
}).filter((i) => i !== null);
console.log(res);
You can use:
abc.replace(/,+/g, ',').replace(/^,|,$/g, '').split(',');
The regEx replaces removes the data that you are not interested in before performing the split.
or
abc.split(',').filter(Boolean);
The filter(Boolean) will remove the items from the array that could be the equivalent of false once the array has been instantiated.
EDIT:
var abc =",,,,,,,,,,,,,,,paul,2,000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var array = abc.replace(/,+/g, ',').replace(/^,|,$/g, '').split(/,([0-9,]+),/);
array = array.filter(Boolean).reduce(function(acc, item) {
if (item.match(/^[0-9,]+$/)) {
acc.push(item);
} else {
acc = acc.concat(item.split(','));
}
return acc;
}, []);

How to check if white spaces stored in an array in javascript?

I have stored a string in an array and want to check for white spaces that also stored in array. So that I can capitalize the each following word.
var arr = [];
arr = str.split("");
for(var i = 0; i < arr.length; i++) {
if(arr[i] === ' ') {
arr[i + 1].toUpperCase();
}
}
You're just missing an assignment:
var arr = [],
str = 'abc def ghi jkl';
arr = str.split("");
for (var i = 0; i < arr.length; i++) {
if (arr[i] === ' ') {
arr[i + 1] = arr[i + 1].toUpperCase();
// ^ You need to save the uppercase letter.
}
}
// Also "uppecase" the first letter
arr[0] = arr[0].toUpperCase();
console.log(arr.join(''));
You can also shorten the code a bit:
var str = 'abc def ghi jkl',
result = str.split(' ') // Split on `[space]`
.map(function(word) { // Do something with every item in the array (every word)
return word.charAt(0).toUpperCase() + // Capitalize the first letter.
word.slice(1); // Add the rest of the word and return it.
})
.join(' '); //Make a string out of the array again.
console.log(result);
You need to set the value of arr[i+1]:
var arr = [];
arr = str.split("");
for(var i=0; i<arr.length; i++)
{
if(arr[i]===' ')
{
arr[i+1]=arr[i+1].toUpperCase();
}
}
You can do it like this
var arr=[];
str="hello hi hello";
arr=str.split("");
arr1=arr.map(function(a,b){if(a==" "){arr[b+1]=arr[b+1].toUpperCase();} return(a)});
arr1[0]=arr[0].toUpperCase();
console.log(arr1);
great piece of code #cerbrus now we can even lowercase other letters in the word except the first one by add :-
var arr = [];
arr = str.split(" ");
str= arr.map(function(word)
{
return word.charAt(0).toUpperCase()+word.slice(1).toLowerCase();
}).join(" ");
return str;
var a = ['', ' ', 'aa '];
a.forEach(function(el){
if(el.trim() == ''){
console.log(el + ' -> white space');
}else{
var index = a.indexOf(el);
a[index] = el.toUpperCase();
console.log(a[index] + ' -> without white space');
}
});
console.log(a);

How to separate the string into two categories in jstl?

i have a string as,
String value = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
Now i need split the names and those values.
I am unable to identify what to do.
I need to print the values as
Output
---
-----------------------------
' Name ' value '
'------------'--------------'
' Bhavani ' 12 '
' Pallavi ' 13 '
' Charanya ' 14 '
' ' '
----------------------------'
I think it can be done in jstl level..
But can anyone help me how to split that string.
you can use str.replace to create an object:
strvalue = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14"
obj={};
strvalue.replace(/(\w+)<>(\w+)/g,function(_,m1,m2){
obj[m1]=m2
})
console.log(obj)
This should do it:
var str = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
str = str.split('<<>>')
for(var i = 0; i < str.length; i++) {
str[i] = str[i].split('<>');
}
alert(str.join("\n"));
first split with <<>>
than split wiht <>
so you will get array with Bhavani , 12 in two indexes.
its simple to show in any way on view.
Personally, I'd store the key-value pairs in an object:
var myObj = {};
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
var stringArray = string.split('<<>>');
for(i in stringArray){
var key = stringArray[i].split('<>')[0];
var value = stringArray[i].split('<>')[1];
myObj[key] = value;
}
console.log('My object looks like', myObj);
Here is my solution, you'll get an array of objects with a name and value inside each object:
let value = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
let splittedString = value.split("<<>>");
let names = [];
splittedString.forEach(function(value) {
let splittedProps = value.split("<>");
names.push({
name: splittedProps[0],
value: splittedProps[1]
});
});
console.log(names);
var str = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
var strArr = str.split("<<>>");
var result = {};
for(var i in strArr){
var p = strArr[i].split("<>");
result[p[0]] = p[1];
}
console.log(result);
First split with <<>>
then split string with <>
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
string = string.split('<<>>');
for(var i = 0; i < string.length; i++) {
string[i] = string[i].split('<>');
}`
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
string = string.split('<<>>');
for(var i = 0; i < string.length; i++) {
string[i] = string[i].split('<>');
}
alert(string.join("\n"));
`
var str = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
var txt = str.split("<<>>").join("|").split("<>").join("|").split("|")
var object=[];
for (var i=0; i<txt.length;i=i+2){
object.push({Name:txt[i],Value:txt[i+1]});
}
console.log(object);

get key value pairs out from the string javascript

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.

Categories