How to merge String? - javascript

It is possible to merge two String with Angularjs function ?:
"123456"
"ABC"
to :
"ABC456"
Thankx

try
var str1 = "123456";
var str2 = "ABC";
console.log(str2 + str1.substring(str2.length));

Use String.prototype.substr function:
var a = "123456";
var b = "ABC";
var res = b + a.substr(b.length);
document.write(res);

Related

How can I split a string into separate keys and values?

I have the following string:
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
I would like to split it out into separate variables like:
name = "Joe";
email = "info#domian.com";
details = "I like Sushi";
I tried something like the below, but it didn't account for everything.
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
splitString = myString.split(':');
myName = splitString[1];
myEmail = splitString[2];
myFood = splitString[3];
console.log('Name: ', myName);
console.log('Email: ', myEmail);
console.log('Food: ', myFood);
I'm wondering if there might be a creative way to do this in JS? Thanks.
This will turn your string into an object with key/value pairs using match() and split(). You can then access the variables using the object, like obj.name or obj.email. There may be a way to fix my regex so that the .shift() method isn't necessary, but it works nonetheless.
let myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
let keys = myString.match(/\w+:/g)
let values = myString.split(/\w+:/);
values.shift(); // remove first item which is empty
let obj = {};
keys.forEach((key, index) => {
obj[key.replace(":", "").toLowerCase()] = values[index].trim()
})
console.log(obj)
// access variables like obj.name or obj.email
Try this:
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
splitString = myString.split(':');
myName = splitString[1].split(' ')[0];
myEmail = splitString[2].split(' ')[0];
myFood = splitString[3]
console.log(myName);
console.log(myEmail);
console.log(myFood);
If you want to get rid of the space in front of "I like Sushi":
details = splitString[3].split(' ');
myDetails = details[1] +' '+ details[2] +' '+ details[3]; console.log(myDetails);
var myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
var arr = myString.replace(/:\s/g, ':').split(" "),
obj = {};
// .replace(/:\s/g,':') Or .replace(/[:\s]/g,':') whichever works better
for (var i = 0; i < arr.length; i++) {
var item = arr[i],
arr2 = item.split(":"),
key = arr2[0].toLowerCase();
obj[key] = arr2[1];
}
console.log(obj["email"]);
//info#domain.com
console.log(obj["details"]);
//I like Sushi

seperate comma seperated string values in string variable

I am trying to extract the string which is like
var str = "[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]"
Desired ouput
a = "/home/dev/servers"
b = "e334ffssfds245fsdff2f"
Here you are:
const str = "[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]";
const object = JSON.parse(str);
const a = object[0];
const b = object[1];
console.log(a);
console.log(b);
The following will work fine for you.
var str = "[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]";
var foo = JSON.parse(str); //Parse the JSON into an object.
var a = foo[0];
var b = foo[1];
Using JSON.parse()
let [a, b] = JSON.parse("[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]")
console.log(a)
console.log(b)

How to remove character from last array element

I need to remove the last element comma in Javascript array
var arr = ["AAA,","BBB,"];
I need the result below
var arr = ["AAA,","BBB"];
Any help is appreciated...
var arr = ["AAA,","BBB,"];
arr[arr.length - 1] = arr[arr.length - 1].replace(',', '');
console.log(arr);
Simply use with replace()
var arr = ["AAA,","BBB,"];
arr[arr.length-1] = arr[arr.length-1].replace(/\,/g,"");
console.log(arr)
One of the other way is this:
var arr = ["AAA,",",BBB,"];
arr.push(arr.pop().replace(/,$/, ''));
console.log(arr);
This answer explains how you can do it using regex:
>> var str = "BBB,"
>> str = str.replace(/,[^,]*$/ , "")
>> str
>> "BBB"
var arr = ["AAA,","BBB,"];
var lastelmnt = arr[(arr.length)-1].replace(',', '');
arr.splice(((arr.length)-1),1,lastelmnt);
Output :
["AAA,", "BBB"]
arr[arr.length-1] = arr[arr.length-1].slice(0,-1)
using JavaScript string split() method & Array splice() method.
DEMO
var arr = ["AAA,","BBB,"];
var arrLastElement = arr[arr.length-1];
var splitStr = arrLastElement.split(',');
var strWithoutComma = splitStr[0];
arr.splice(arr.length-1);
arr.push(strWithoutComma);
console.log(arr);

Regex for creating an array from String

I have a string as follows
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
I want to get three arrays from above string as follows
var arr1 = ["series-3","series-5","series-6"];
var arr2 = ["a3","a4","a5"];
var arr3 = ["class a", "class b"];
What regex should I use to achieve this?
Can this be done without regex?
Use String#split() method
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// split string based on comma followed by [
var temp = str.split(/,(?=\[)/);
// remove [ and ] from string usning slice
// then split using , to get the result array
var arr1 = temp[0].slice(1, -1).split(',');
var arr2 = temp[1].slice(1, -1).split(',');
var arr3 = temp[2].slice(1, -1).split(',');
console.log(arr1, arr2, arr3);
Or same method with some variation
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Remove [ at start and ] at end using slice
// and then split string based on `],[`
var temp = str.slice(1, -1).split('],[');
// then split using , to get the result array
var arr1 = temp[0].split(',');
var arr2 = temp[1].split(',');
var arr3 = temp[2].split(',');
console.log(arr1, arr2, arr3);
RegEx and String methods can be used. It's better to create an object and store individual arrays inside that object.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Match anything that is inside the `[` and `]`
var stringsArr = str.match(/\[[^[\]]*\]/g);
// Result object
var result = {};
// Iterate over strings inside `[` and `]` and split by the `,`
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var stringsArr = str.match(/\[[^[\]]*\]/g);
var result = {};
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
To create the global variables(Not recommended), just remove var result = {}; and replace result by window in the forEach.
I would prefer to do it like this
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]",
arrs = str.match(/[^[]+(?=])/g).map(s => s.split(","));
console.log(arrs);
Just for the fun of it, another way where we add the missing quotes and use JSON.parse to convert it to a multidimensional array.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var result = JSON.parse("[" + str.replace(/\[/g,'["').replace(/\]/g,'"]').replace(/([^\]]),/g,'$1","') + "]");
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);

JavaScript split string in to two variables at character by number

How to split a string at a specific point defined by a number?
In example generate two variables, t1 and t2 from the string '123456' and have it split at character 3 so t1's value is '123' and t2's value is '456'...
var s0 = '123456';
console.log(s1);//123
console.log(s2);//456
I'd suggest:
var s0 = '123456',
t1 = s0.substring(0, s0.indexOf(3) + 1),
t2 = s0.substring(s0.indexOf(3) + 1);
References:
String.prototype.indexOf().
String.prototype.substring().
If you meant the 3rd character:
var ch = 3;
var s0 = "123456";
var s1 = s0.substr(0,ch); // will be '123'
var s2 = s0.substr(ch); // will be '456'
You can just do this.
var s0 = '123456';
var arr = s0.split('3');
var t1 = arr[0] + '3', t2 = arr[1];
Something like:
var foo = '123456'
,bar = [foo.slice(0,3), foo.slice(3)];
//=> bar now ["123", "456"]
Extend the String prototype:
String.prototype.splitAt = function(n) {
return n && n < this.length
? [this.slice(0,n), this.slice(n)]
: this;
}
// usages
'123456'.splitAt(3); //=> ['123', '456']
'123456'.splitAt(2); //=> ['12', '3456']
'123456'.splitAt(12); //=> '123456'
'123456'.splitAt(); //=> '123456'
Try
var s0 = "123456"
, s1 = s0.slice(0, 3); // first 3 characters in string , `123`
, s2 = s0.slice(- (s0.length - s1.length) ); // remainder of string , `456`(+)
console.log(s0, s1, s2)
var s = '123456';
var sos = 3;//number to split by
var t1 = '';
var t2 = '';
for (var i = 0; i < s.length; i++)
{
if (i<sos) {t1 += s[i];}
else {t2 += s[i];}
}
console.log('t1 = '+t1);
console.log('t2 = '+t2);

Categories