Javascript to cut same second character on a text - javascript

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);

Related

Split a single array with respect to comma in 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"]

Javascript How to get first three characters of a string

This may duplicate with previous topics but I can't find what I really need.
I want to get a first three characters of a string. For example:
var str = '012123';
console.info(str.substring(0,3)); //012
I want the output of this string '012' but I don't want to use subString or something similar to it because I need to use the original string for appending more characters '45'. With substring it will output 01245 but what I need is 01212345.
var str = '012123';
var strFirstThree = str.substring(0,3);
console.log(str); //shows '012123'
console.log(strFirstThree); // shows '012'
Now you have access to both.
slice(begin, end) works on strings, as well as arrays. It returns a string representing the substring of the original string, from begin to end (end not included) where begin and end represent the index of characters in that string.
const string = "0123456789";
console.log(string.slice(0, 2)); // "01"
console.log(string.slice(0, 8)); // "01234567"
console.log(string.slice(3, 7)); // "3456"
See also:
What is the difference between String.slice and String.substring?

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

Return only text after last underscore in JavaScript string

If I have a string like so:
var str = 'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti';
How can I get just the last part of the string after the last underscore?
And in the case there are no underscores just return the original string.
In this case I want just 'hunti'
var index = str.lastIndexOf("_");
var result = str.substr(index+1);
It's very simple. Split the string by the underscore, and take the last element.
var last = str.split("_").pop();
This will even work when the string does not contain any underscores (it returns the original string, as desired).
You can use a regular expression:
'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti'.match(/[^_]*$/)[0];

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