javascript: get everything after certain characters from a string? - javascript

I'm trying to get everything after certain characters in a string.
But I have no idea why with my, when I alert(); the result, there is a comma before the string!
Here is a working FIDDLE
And this is my code:
var url = "mycool://?string=mysite.com/username_here80";
var urlsplit = url.split("mycool://?string=");
alert(urlsplit);
any help would be appreciated.

Split separates the string into tokens separated by the delimiter. It always returns an array one longer than the number of tokens in the string. If there is one delimiter, there are two tokens—one to the left and one to the right. In your case, the token to the left is the empty string, so split() returns the array ["", "mysite.com/username_here80"]. Try using
var urlsplit = url.split("mycool://?string=")[1]; // <= Note the [1]!
to retrieve the second string in the array (which is what you are interested in).
The reason you are getting a comma is that converting an array to a string (which is what alert() does) results in a comma-separated list of the array elements converted to strings.

The split function of the string object returns an Array of elements, based on the splitter. In your case - the returned 2 elements:
var url = "http://DOMAIN.com/username_here801";
var urlsplit = url.split("//");
console.log(urlsplit);
The comma you see is only the representation of the Array as string.
If you are looking for to get everything after a substring you better use the indexOf and slice:
var url = "http://DOMAIN.com/username_here801";
var splitter = '//'
var indexOf = url.indexOf(splitter);
console.log(url.slice(indexOf+splitter.length));

I'd use a simple replace..
var s = "mycool://?string=mysite.com/username_here80";
var ss = s.replace("mycool://?string=", "");
alert(ss);

Related

Why is the first match empty when using a split regex? [duplicate]

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

Split and grab text before second hyphen

I have the following text string:
test-shirt-print
I want to filter the text string so that it only returns me:
test-shirt
Meaning that everything that comes after the second hyphen should be removed including the hyphen.
I am thinking that the solution could be to split on hyphen and somehow select the two first values, and combine them again.
I am unaware of which functionality is best practice to use here, I also thinking that if it would be possible to use a regular expression in order to be able to select everything before the second hyphen.
You can use split slice and join together to remove everything after the second hyphen
var str = "test-shirt-print";
console.log(str.split("-").slice(0, 2).join('-'))
You can try with String.prototype.slice()
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
and String.prototype.lastIndexOf()
The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.
var str = 'test-shirt-print';
var res = str.slice(0, str.lastIndexOf('-'));
console.log(res);
You can also use split() to take the first two items and join them:
var str = 'test-shirt-print';
var res = str.split('-').slice(0,2).join('-');
console.log(res);

parse multiple json string into one object in javascript

I have a json output where it gets two strings with format such as
[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]
[{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
I want to parse these strings into one object. I have used the JSON.parse(data) but its giving me first string in object and not the all strings. How do I achieve this.
i want the output should be
[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"},
{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
I guess you'd want an array with both of the objects inside, otherwise, please specify what is your expected output.
If you are unable to modify the JSON string received to make it look like a proper array, I'd substitute the '][' for a comma ',' so you can parse the JSON string and receive back an array with two objects inside, like so:
original = '[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}][{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]';
replaced = original.replace('][', ',');
parsed = JSON.parse(replaced);
Edited:
Just in case your input contains a line break between the closing and opening square brackets, your substitution should be like that:
replaced = original.replace(']\n[', ',');
2nd edit:
If your input contains more than two lines like these, there is no problem, your replace call will substitute every one of the matches if you write it like that:
replaced = original.replace(/\]\[/g, ',');
This is a regular expression that substitutes every occurence of ][ (expressed as \]\[ because these are special characters for regular expressions), with the help of the global flag specified at the end of the regular expression.
You can do:
var obj1 = [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]
var obj2 = [{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
/* or */
var obj1 = JSON.parse('[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]')
var obj2 = JSON.parse('[{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]')
// then flatten into one array
var combined = [].concat.apply([], [obj1, obj2])
console.log(combined);
// [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}, {"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]

Whats wrong with this regex logic

I am trying to fetch the value after equal sign, its works but i am getting duplicated values , any idea whats wrong here?
// Regex for finding a word after "=" sign
var myregexpNew = /=(\S*)/g;
// Regex for finding a word before "=" sign
var mytype = /(\S*)=/g;
//Setting data from Grid Column
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
var newtype = mytype.exec(strNew);
alert(matchNew);
https://jsfiddle.net/6vjjv0hv/
exec returns an array, the first element is the global match, the following ones are the submatches, that's why you get ["=20", "20"] (using console.log here instead of alert would make it clearer what you get).
When looking for submatches and using exec, you're usually interested in the elements starting at index 1.
Regarding the whole parsing, it's obvious there are better solution, like using only one regex with two submatches, but it depends on the real goal.
You can try without using Regex like this:
var val = 'QCById=20';
var myString = val.substr(val.indexOf("=") + 1);
alert(myString);
Presently exec is returning you the matched value.
REGEXP.exec(SOMETHING) returns an array (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec).
The first item in the array is the full match and the rest matches the parenthesized substrings.
You do not get duplicated values, you just get an array of a matched value and the captured text #1.
See RegExp#exec() help:
If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.
Just use the [1] index to get the captured text only.
var myregexpNew = /=(\S*)/g;
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
if (matchNew) {
console.log(matchNew[1]);
}
To get values on both sides of =, you can use /(\S*)=(\S*)/g regex:
var myregexpNew = /(\S*)=(\S*)/g;
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
if (matchNew) {
console.log(matchNew[1]);
console.log(matchNew[2]);
}
Also, you may want to add a check to see if the captured values are not undefined/empty since \S* may capture an empty string. OR use /(\S+)=(\S+)/g regex that requires at least one non-whitespace character to appear before and after the = sign.

JavaScript regex to extract different parts of a string

This is an interesting one - I am looking for a JavaScript regex solution to extract different parts from a string. Any input is much appreciated.
Example -
";1XYZ123_UK;1;2.3;evt14=0.0|evt87=0.0,;1XYZ456_UK;4;5.6;evt14=0.0;fly;0;0;;;"
I am trying to extract just these bits from the string ignoring the rest-
“1XYZ123_UK;2;3;1XYZ456_UK;4;5.6;”
Basically extract anything starting with 1XYZ up until it encounters 'evt'.
var s = ';1XYZ123_UK;1;2e.3;evt14=0.0|evt87=0.0,;1XYZ456_UK;4;5.6;evt14=0.0';
var r = s.match(/1XYZ((?!evt).)*/g);
Will give you your desired strings:
["1XYZ123_UK;1;2e.3;", "1XYZ456_UK;4;5.6;"]
var s= ";1XYZ123_UK;1;2.3;evt14=0.0|evt87=0.0,;1XYZ456_UK;4;5.6;evt14=0.0"
s = s.replace(/(evt.+?(?:\||;|$))/g, "");
console.log(s) // ";1XYZ123_UK;1;2.3;1XYZ456_UK;4;5.6;"
Use groups ((...)) to capture parts of the matched string. After a successful match the substrings captured can be accessed via the array returned from String.match or Regex.exec.
The first element of the array (index 0) is the whole match, the next (index 1) is the first capture.
Eg.
var re = /1XY(.*)evt/
var result = theString.match(re)
then, if there is a match (result is not null) then
result[0]
will be the whole match (starting 1XY and ending evt) while
result[1]
will be the text between those strings.

Categories