Parse string in javascript - javascript

How can I parse this string on a javascript,
var string = "http://www.facebook.com/photo.php?fbid=322916384419110&set=a.265956512115091.68575.100001022542275&type=1";
I just want to get the "265956512115091" on the string. I somehow parse this string but, still not enough to get what I wanted.
my code:
var newstring = string.match(/set=[^ ]+/)[0];
returns:
a.265956512115091.68575.100001022542275&type=1

try this :
var g=string.match(/set=[a-z]\.([^.]+)/);
g[1] will have the value
http://jsbin.com/anuhog/edit#source

You could use split() to modify your code like this:
var newstring = string.match(/set=[^ ]+/)[0].split(".")[1];
For a more generic approach to parsing query strings see:
Parse query string in JavaScript
Using the example illustrated there, you would do the following:
var newstring = getQueryVariable("set").split(".")[1];

You can use capturing group in the regex.
const str = 'http://www.facebook.com/photo.php?fbid=322916384419110&set=a.265956512115091.68575.100001022542275&type=1';
console.log(/&set=(.*)&/.exec(str)[1]);

Related

javascript split string function not working

I am trying to split a string:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = device_data.split('*');
But it's not working. it's just displaying this string
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = str.split('*');
console.dir(res)
,HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#,HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555
Instead of creating an array with two elements.
IMHO, you want something like this:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
splitStrArr = str.split('*').filter(str => str != "")
console.log(splitStrArr)
console.log(splitStrArr[0])
console.log(splitStrArr[1])
You are getting a string with a period in the beginning because whatever you are doing leads to the result of String#split being converted to a string. String#split returns an array. An array converted to a string is of the form of element0,element1,element2 ... elements separated by commas.
The result of String#split in your case is ["",...] with 3 elements since your string begins with the character '*' you are searching, so String#split will create an empty string as the first element of the returned array. So the result is exactly as expected, and String#split is working as intended.
get rid of the first character of the string,
mystring.substr(1).split('*')
get rid of the empty strings
mystring.split('*').filter(s=>s!='')
to obtain the desired result.
You can use:
var res = str.split("#");
You can check in Javascript console in browser itself.
As a suggestion/ idea, you can always use the browser console, for example, Chrome browser, to execute simple scripts like these.
This way, you can save time, as it is easier to check your data structures, their internal data.
If you try
var res = str.split('*');
you obtain three elements:
res[0] is '' (empty string)
res[1] is 'HQ,61...'
res[2] is 'HQ,...'

Substring a part of a string using angularjs

I have a string like this string(1), I want to get substring remove the last part to obtain just string any suggestions please!!
PS.the string could be: sringggg(125).
You can use various options to get the desired string.
//With regular expression with split() and fetch the first element of array
console.log('sringggg(125)'.split(/\(\d+\)/)[0]);
//Using string with split() and fetch the first element of array
console.log('sringggg(125)'.split('(')[0]);
//Using substr and indexOf
var str = 'sringggg(125)'
console.log(str.substr(0, str.indexOf('(')));
References
String.prototype.split()
String.prototype.indexOf()
If string is always in same pattern and ' ( ' is a separator use split .
var string = 'string(1)'
var result = string .split('(')[0];
Try using regexp
var tesst = "string(1)"
var test = tesst.match(/^[^\(]+/);
// test = "string"

Get portion of a string using Javascript

I have a string (from the pathname in the url) and I am trying to pull out part of it, but I'm having trouble.
This is what I have so far:
^(/svc_2/pub/(.*?).php)
The string is:
/svc_2/pub/stats/dashboard.php?ajax=1
How can I get a regex that returns /pub/stats/dashboard only?
If it's always that format (I'm assuming the /svc_2/ is always there) this should do it.
var s = "/svc_2/pub/stats/dashboard.php?ajax=1";
var match = s.match(/\/svc_2(.+)\./)[1];
But not if anything comes before that.
For this, using a regex is too much, but here is:
var string = "/svc_2/pub/stats/dashboard.php?ajax=1";
console.log(string.replace(/.*(\/pub.*)\.php.*$/,"$1"));
But you can do it, without a regex, like this
console.log(string.substr(6,string.indexOf(".php")-6));
In both cases, the console.log will give you /pub/stats/dashboard
This is not very flexible, but should work in this specific case.
var basedir = '/svc_2/', str = '/svc_2/pub/stats/dashboard.php?ajax=1';
str = str.substring(basedir.length, str.indexOf('.'));
alert(str);

Simple Javascript string manipulation

I have a string that will look something like this:
I'm sorry the code "codehere" is not valid
I need to get the value inside the quotes inside the string. So essentially I need to get the codehere and store it in a variable.
After some researching it looks like I could loop through the string and use .charAt(i) to find the quotes and then pull the string out one character at a time in between the quotes.
However I feel there has to be a simpler solution for this out there. Any input would be appreciated. Thanks!
You could use indexOf and lastIndexOf to get the position of the quotes:
var openQuote = myString.indexOf('"'),
closeQuote = myString.lastIndexOf('"');
Then you can validate they are not the same position, and use substring to retrieve the code:
var code = myString.substring(openQuote, closeQuote + 1);
Regex:
var a = "I'm sorry the code \"codehere\" is not valid";
var m = a.match(/"[^"]*"/ig);
alert(m[0]);
Try this:
var str = "I'm sorry the code \"cod\"eh\"ere\" is not valid";
alert(str.replace(/^[^"]*"(.*)".*$/g, "$1"));
You could use Javascript's match function. It takes as parameter, a regular expression. Eg:
/\".*\"/
Use regular expressions! You can find a match using a simple regular expressions like /"(.+)"/ with the Javascript RegExp() object. Fore more info see w3schools.com.
Try this:
var msg = "I'm sorry the code \"codehere\" is not valid";
var matchedContent = msg.match(/\".*\"/ig);
//matchedContent is an array
alert(matchedContent[0]);
You should use a Regular Expression. This is a text pattern matcher that is built into the javascript language. Regular expressions look like this: /thing to match/flags* for example, /"(.*)"/, which matches everything between a set of quotes.
Beware, regular expressions are limited -- they can't match nested things, so if the value inside quotes contains quotes itself, you'll end up with a big ugly mess.
*: or new RegExp(...), but use the literal syntax; it's better.
You could always use the .split() string function:
var mystring = 'I\'m sorry the code "codehere" is not valid' ;
var tokens = [] ;
var strsplit = mystring.split('\"') ;
for(var i=0;i<strsplit.length;i++) {
if((i % 2)==0) continue; // Ignore strings outside the quotes
tokens.push(strsplit[i]) ; // Store strings inside quotes.
}
// Output:
// tokens[0] = 'codehere' ;

Splitting string in javascript

How can I split the following string?
var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";
If I use str.split(",") then I won't be able to get strings which contain commas.
Whats the best way to split the above string?
I assume it's actually:
var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';
because otherwise it wouldn't even be valid JavaScript.
If I had a string like this I would parse it as an incomplete JSON which it seems to be:
var obj = JSON.parse('{'+str+'}');
and then use is as a plain object:
alert(obj.test1); // says: hello,hi
See DEMO
Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?
Update 2: Also, is it only me who sees it as a JSON without curly braces?
Though not clear with your input. Here is what I can suggest.
str.split('","');
and then append the double quotes to each string
str.split('","'); Difficult to say given the formatting
if Zed is right though you can do this (assuming the opening and closing {)
str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.
The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:
var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
arr.push(i);
}
Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.

Categories

Resources