Split a single array with respect to comma in javascript - javascript

I am getting an array of single string $scope.Obj= ["Talking Spanish,Spanish food,Spanish things,Football"];
The split should be by watching ,
I need to break it down = ["Talking Spanish","Spanish food","Spanish things","Football"];
How can I do it using javascript?

You can use split
let arr = ["Talking Spanish,Spanish food,Spanish things,Football"];
let op = arr[0].split(',')
console.log(op)

You can split 0th index of $scope.Obj with , and reassign to $scope.Obj.
$scope={};
$scope.Obj= ["Talking Spanish,Spanish food,Spanish things,Football"];
$scope.Obj=$scope.Obj[0].split(",")
console.log($scope.Obj);

str.split(separator, limit)
The above is common syntax to split a array
https://medium.freecodecamp.org/how-to-make-your-react-native-app-respond-gracefully-when-the-keyboard-pops-up-7442c1535580

The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
In the following example, split() looks for spaces in a string and returns the first 3 splits that it finds.
var myString = 'Hello World. How are you doing?';
var splits = myString.split(' ', 3);
console.log(splits);
This script displays the following:
["Hello", "World.", "How"]

Related

Splitting String and taking out specific elements in node js

I have Sample String like this
"Organisation/Guest/images/guestImage.jpg"
I need to take out Organisation,Guest separately.
I have tried split() but can't get desired output.
var str = "Organisation/Guest/images/guestImage.jpg";
var res = str.split("/");
console.log(res[0]);
console.log(res[1]);
You can use of String.replace() along with regex
const regex = /Organisation\/|\/Organisation/;
console.log('Organisation/Guest/images/guestImage.jpg'.replace(regex, ''));
console.log('Guest/Organisation/images/guestImage.jpg'.replace(regex, ''));
console.log('Guest/images/guestImage.jpg/Organisation'.replace(regex, ''));
var yourString = "Organisation/Guest/images/guestImage.jpg";
yourString.split('/')
// this returns all the words in an array
yourString[0] // returns Organisation
yourString[1] // returns Guest and so on
When you run .split() on a string, it will return a new array with all the words in it. In the code I am splitting by the slash /
Then I save the new array in a variable. Now you should know we can access array properties like this: array[0] where 0 is the first index position or the first word, and so on.

Javascript to cut same second character on a text

For example I have text:
var x="default_1305, default_1695, default_1805";
I want to cut before the second comma to get this text:"default_1305, default_1695".
How can I do this?
var x="default_1305, default_1695, default_1805";
string can be split by , like below:
var res = x.split(",", 2);
Note 2 here in the second param.
And if needed as string, then
var res_string = res.join(",");
Edit:
.split() on MDN
Syntax
str.split([separator[, limit]])
Parameters
separator
Optional. Specifies the character(s) to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.
limit
Optional. Integer specifying a limit on the number of splits to be found. The split() method still splits on every match of separator, until the number of split items match the limit or the string falls short of separator.
Convert string to array and get first two elements
var x="default_1305, default_1695, default_1805";
var b = x.split(',')
var c = b[0]+","+b[1]
You can also use .slice() to get the parts you need, eg:
// added an extra item to distinguish first-two vs all-but-last
var x="default_1305, default_1695, default_1805, default_1962";
// get first two
var result = x.split(",").slice(0,2).join(",");
console.log(result);
// get all but last
var result = x.split(",").slice(0,-1).join(",");
console.log(result);

Regular Expression to get the last word from TitleCase, camelCase

I'm trying to split a TitleCase (or camelCase) string into precisely two parts using javascript. I know I can split it into multiple parts by using the lookahead:
"StringToSplit".split(/(?=[A-Z])/);
And it will make an array ['String', 'To', 'Split']
But what I need is to break it into precisely TWO parts, to produce an array like this:
['StringTo', 'Split']
Where the second element is always the last word in the TitleCase, and the first element is everything else that precedes it.
Is this what you are looking for ?
"StringToSplit".split(/(?=[A-Z][a-z]+$)/); // ["StringTo", "Split"]
Improved based on lolol answer :
"StringToSplit".split(/(?=[A-Z][^A-Z]+$)/); // ["StringTo", "Split"]
Use it like this:
s = "StringToSplit";
last = s.replace(/^.*?([A-Z][a-z]+)(?=$)/, '$1'); // Split
first = s.replace(last, ''); // StringTo
tok = [first, last]; // ["StringTo", "Split"]
You could use
(function(){
return [this.slice(0,this.length-1).join(''), this[this.length-1]];
}).call("StringToSplit".split(/(?=[A-Z])/));
//=> ["StringTo", "Split"]
In [other] words:
create the Array using split from a String
join a slice of that Array without the last element of that
Array
add that and the last element to a final Array

How to convert a string into an array?

How do I convert the following string to an array?
String:
var string = "[energy,people,coding,vein]";
Array:
var array = ["energy","people","coding","vein"];
The easiest way to convert a string of comma separated values into an array is just to use split.
string1 = "testing,stuff";
arr = string1.split(","); // arr now equals ["testing", "stuff"]
The opening and closing brackets you could just get rid of using the substr method, or just leaving them off initially if you have that option
This is a two part process:
Remove the brackets with String.substr() (assuming the first and last characters in your string are brackets).
Use String.split() to break the string into an array.
This is the most efficient way to convert the string '[energy,people,coding,vein]' into an array:
var String1 = '[energy,people,coding,vein]',
array = String1.substr(1, String1.length - 2).split(',');
console.log(array); // ["energy", "people", "coding", "vein"]

String split returns an array with more elements than expected (empty elements)

I don't understand this behaviour:
var string = 'a,b,c,d,e:10.';
var array = string.split ('.');
I expect this:
console.log (array); // ['a,b,c,d,e:10']
console.log (array.length); // 1
but I get this:
console.log (array); // ['a,b,c,d,e:10', '']
console.log (array.length); // 2
Why two elements are returned instead of one? How does split work?
Is there another way to do this?
You could add a filter to exclude the empty string.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(function(el) {return el.length != 0});
A slightly easier version of #xdazz version for excluding empty strings (using ES6 arrow function):
var array = string.split('.').filter(x => x);
This is the correct and expected behavior. Given that you've included the separator in the string, the split function (simplified) takes the part to the left of the separator ("a,b,c,d,e:10") as the first element and the part to the rest of the separator (an empty string) as the second element.
If you're really curious about how split() works, you can check out pages 148 and 149 of the ECMA spec (ECMA 262) at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Use String.split() method with Array.filter() method.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(item => item);
console.log(array); // [a,b,c,d,e:10]
console.log (array.length); // 1
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
trim the trailing period first
'a,b,c,d,e:10.'.replace(/\.$/g,''); // gives "a,b,c,d,e:10"
then split the string
var array = 'a,b,c,d,e:10.'.replace(/\.$/g,'').split('.');
console.log (array.length); // 1
That's because the string ends with the . character - the second item of the array is empty.
If the string won't contain . at all, you will have the desired one item array.
The split() method works like this as far as I can explain in simple words:
Look for the given string to split by in the given string. If not found, return one item array with the whole string.
If found, iterate over the given string taking the characters between each two occurrences of the string to split by.
In case the given string starts with the string to split by, the first item of the result array will be empty.
In case the given string ends with the string to split by, the last item of the result array will be empty.
It's explained more technically here, it's pretty much the same for all browsers.
According to MDN web docs:
Note: When the string is empty, split() returns an array containing
one empty string, rather than an empty array. If the string and
separator are both empty strings, an empty array is returned.
const myString = '';
const splits = myString.split();
console.log(splits);
// ↪ [""]
Well, split does what it is made to do, it splits your string. Just that the second part of the split is empty.
Because your string is composed of 2 part :
1 : a,b,c,d,e:10
2 : empty
If you try without the dot at the end :
var string = 'a,b,c:10';
var array = string.split ('.');
output is :
["a,b,c:10"]
You have a string with one "." in it and when you use string.split('.') you receive array containing first element with the string content before "." character and the second element with the content of the string after the "." - which is in this case empty string.
So, this behavior is normal. What did you want to achieve by using this string.split?
try this
javascript gives two arrays by split function, then
var Val = "abc#gmail.com";
var mail = Val.split('#');
if(mail[0] && mail[1]) { alert('valid'); }
else { alert('Enter valid email id'); valid=0; }
if both array contains length greater than 0 then condition will true

Categories

Resources