How to use string.split( ) for the following string in javascript - javascript

I have the following string: (17.591257793993833, 78.88544082641602) in Javascript
How do I use split() for the above string so that I can get the numbers separately.
This is what I have tried (I know its wrong)
var location= "(17.591257793993833, 78.88544082641602)";
var sep= location.split("("" "," "")");
document.getElementById("TextBox1").value= sep[1];
document.getElementById("Textbox2").value=sep[2];
Suggestions please

Use regular expression, something as simple as following would work:
// returns and array with two elements: [17.591257793993833, 78.88544082641602]
"(17.591257793993833, 78.88544082641602)".match(/(\d+\.\d+)/g)

You could user Regular Expression. That would help you a lot. Together with the match function.
A possible Regexp for you might be:
/\d+.\d+/g
For more information you can start with wiki: http://en.wikipedia.org/wiki/Regular_expression

Use the regex [0-9]+\.[0-9]+. You can try the regex here.
In javascript you could do
var str = "(17.591257793993833, 78.88544082641602)";
str.match(/(\d+\.\d+)/g);
Check it.

If you want the values as numbers, i.e. typeof x == "number", you would have to use a regular expression to get the numbers out and then convert those Strings into Numbers, i.e.
var numsStrings = location.match(/(\d+.\d+)/g),
numbers = [],
i, len = numsStrings.length;
for (i = 0; i < len; i++) {
numbers.push(+numsStrings[i]);
}

Related

Parse a string representing an array of floats

I have a string as such:
string = "[x,y,z]"
Where x, y and z are valid javascript floats as strings. Some examples:
-0.9999
1.
1.00000000000E-5
-1E5
What is the most efficient (fastest) way to parse this string into an actual javascript array of floats without using Eval?
Now I do this:
parseFloatArray = function(string){
// isolate string by removing square brackets
string = string.substr( 1, string.length-2 )
// create array with string split
var array = string.split(',');
// parse each element in array to a float
for (var i = 0, il = array.length; i < il; i++){
array[i] = parseFloat(array[i]);
}
// return the result
return array
}
It is important that the solution works correctly for the above examples.
I also tried with JSON.parse which seemed perfect at first, but it returns a SyntaxError for the second example 1. where there is nothing following the decimal separator.
I prepared a fiddle for testing.
Instead of this
array[i] = parseFloat(array[i]);
try
array[i] = +array[i];
Above handles all the test cases pretty well.
Here is the working fiddle
Try this :
str = "[-0.9999, 1., 1.00000000000E-5,-1E5]";
str.slice(1, str.length-1).split(',').map(Number);
// [-0.9999, 1, 0.00001, -100000]
parseFloat basic syntax is parseFloat(string). https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
If you think the input values are only numbers you can use Number(x) rather than parseFloat.
Also, you might get different values upon parsing because all floating-point math is based on the IEEE [754] standard. so use toPrecision() method to customize your values- https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Number/toPrecision.
Instead of you writing the for loop, you can always use the javascript built in array.prototypes
var string = "[1.,-0.9999,-1.00000E-5]";
var array = string.substr( 1, string.length-2 ).split(',');
console.log(array.map(function(i){return parseFloat(i);}));
you can also use the unary operator instead of parseFloat().
console.log(array.map(function(i){return +i;}));
Most efficient to extract is replacing and splitting.
var str = "[312.413,436.6546,34.1]"; // string
str = () => str.replace(/\[|\]/g, "").split(","); //[312.413, 4...] Array
most eficient to parse is just preceed the string with a "+", that will numerify it and, since javascript works with floats as primitives (and not integers), they will be automatically parsed.
var a = "1.00000000000E-5";
console.log( +a ); // 0.00001

Replace double commas until there are some

I am trying to replace all double commas with ,null,
The problem is that i need to keep doing it while it is replacing it. I am thinking about adding a loop but is there any other more eficient alternative?
var test = "[1,2,,,3,4,,,,,,5,6]".replace(/,{2}/g, ",null,");
alert(test);
The result should be:
"[1,2,null,null,3,4,null,null,null,null,null,5,6]"
But is instead:
[1,2,null,,3,4,null,,null,,null,5,6]
So I would have to create a loop and do it until all double commas are done. Not sure if there is any other way?
As a side info, this is so that I can afterwards do:
var myArray = $.parseJSON(test);
Which currently it fails which I'm guessing that it's because it is not valid json.
Single regex:
"[AB,,,CD,,,,,,EF]".replace(/,(?=,)/g, ',null');
demo
Here we use the ?= lookahead to find 2 commas ("comma with a comma after it") but match and replace only the first.
Edit:
You seem to be interested in speed, here are some tests.
str.split(',').map(function(x) { return x ? x : 'null' }).join(',');
FIDDLE
splits the string by commas, then map() iterates and returns each value from the callback, and the ternary returns x (the value) if thruthy and the string 'null' if falsy, which an empty string is, then join it back together again.
You can do this:
var test = "[1,2,,,3,4,,,,,,5,6]".split(',').join(',|').replace(/\|,/g,"null,");
alert(test.replace(/\|/g,""));
It alerts:
[1,2,null,null,3,4,null,null,null,null,null,5,6]
Demo: http://jsfiddle.net/AmitJoki/Zuv38/
Not sure if regex could handle that without looping.
Alternative solution is to split is into an array: '1,2,,,3,4,,,,,,5,6'.split(','); and then loop through it and replace all empty strings with null and then join it back.
So, something like this:
var s = '1,2,,,3,4,,,,,,5,6';
var a = s.split(',');
for (var i = 0; i < a.length; i++) {
if (a[i] == "") {
a[i] = "null";
}
}
s = '[' + a.join(',') + ']';
See it here: http://jsfiddle.net/fVMLv/1/
Try this
var str = "1,2,,,3,4,,,,,,5,6";
str = str.split(',');
var strResult ='';
$(str).each(function(){
if(this==''){
strResult +='null,';
}
else{
strResult +=this+',';
}
});
strResult = strResult.substring(0,strResult.length-1);
alert(strResult);
DEMO
The problem is with the double commas occurring consecutively.
,,,, -> will be taken as 2 sets of double commas by that RegExp. So, result will be:-
,null,,null, -> note that the occurrence of another double comma in between is skipped, since the RegEx is greedy (2nd comma is already used, which is not used again together with 3rd comma. rather 3rd and 4th are used together).
var test = "[AB,,,CD,,,,,,EF]".replace(/,,/g, ",null,").replace(/,,/g, ",null,");
alert(test);
So, with this RegExp, calling it twice will fix this.

RegEx get value from _GET request

I'll read more about RegEx in near future, but for now i can't get RegEx for the following:
?filter=aBcD07_1-&developer=true
Need to get only aBcD07_1-, without other.
Can you please help and provide me a RegEx for javascript
Thanks!
A simple substring and indexOf should do the trick.
var startIndex = str.indexOf('filter=') + 7;
str.substring(startIndex, str.indexOf('&', startIndex)); // returns "aBcD07_1"
Try with this one:
var rx = /[?&]filter=([a-zA-Z0-9_-]+).*/g;
var result = rx.exec(yourGetStr);
if (result && result.length == 2) {
alert (result[1]);
}
This regular expression will work even when filter is not the first query parameter.

Removing string using javascript

I have a string like
var test="ALL,l,1,2,3";
How to remove ALL from string if it contains using javascript.
Regards,
Raj
you can use js replace() function:
http://www.w3schools.com/jsref/jsref_replace.asp
so:
test.replace("ALL,", "");
If the word All can appear anywhere or more than once (e.g. "l,1,ALL,2,3,ALL") then have such code:
var test = "l,1,ALL,2,3,ALL"
var parts = test.split(",");
var clean = [];
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if (part !== "ALL")
clean.push(part);
}
var newTest = clean.join(",");
After this the variable newTest will hold the string without ALL.
If all you want to do is remove occurrences of the string "ALL" from another string, you can use the JavaScript String object's replace method:
test.replace("ALL","");
I'm not really sure if you want to remove all instances of capital letters from your string, but you are probably looking at using a regular expression such as s.replace(/[A-Z]/g,"") where s is the string.
Looking up javascript RegExp will give more indepth details.
use:
test.replace ( 'ALL,', '' );

Complex regex to split up a string

I need some help with a regex conundrum pls. I'm still getting to grips with it all - clearly not an expert!
Eg. Say I have a complex string like so:
{something:here}{examp.le:!/?foo|bar}BLAH|{something/else:here}:{and:here\\}(.)}
First of all I want to split the string into an array by using the pipe, so it is effectively like:
{something:here}{examp.le:!/?foo|bar}BLAH
and
{something/else:here}:{and:here\\}(.)}
But notice that there is a pipe within the curly brackets to ignore... so need to work out the regex expression for this. I was using indexOf originally, but because I now have to take into account pipes being within the curly brackets, it complicates things.
And it isn't over yet! I also then need to split each string into separate parts by what is within the curly brackets and not. So I end up with 2 arrays containing:
Array1
{something:here}
{examp.le:!/?foo|bar}
BLAH
Array2
{something/else:here}
:
{and:here\\}(.)}
I added a double slash before the first closing curly bracket as a way of saying to ignore this one. But cannot figure out the regex to do this.
Can anyone help?
Find all occurrences of "string in braces" or "just string", then iterate through found substrings and split when a pipe is encountered.
str = "{something:here}{examp.le:!/?foo|bar}BLAH|{something/else:here}:{and:here\\}(.)}"
var m = str.match(/{.+?}|[^{}]+/g)
var r = [[]];
var n = 0;
for(var i = 0; i < m.length; i++) {
var s = m[i];
if(s.charAt(0) == "{" || s.indexOf("|") < 0)
r[n].push(s);
else {
s = s.split("|");
if(s[0].length) r[n].push(s[0]);
r[++n] = [];
if(s[1].length) r[n].push(s[1]);
}
}
this expr will be probably better to handle escaped braces
var m = str.match(/{?(\\.|[^{}])+}?/g

Categories