Get the substring between two substrings in a string [Javascript] - javascript

Get 3 or 57 in these examples
I have a list of objects that contain JSON values of these:
For some reason I will skip, the result will be as follows and I want to get the value of the CubicMillimeters by using Regex. How will I do this?
var json1 = "{
"CubicMillimeters": 3,
"Longtitude": 342.152345,
"Latitude": 321.332331
}"
var json2 = "{
"CubicMillimeters": 57,
"Longtitude": 342.152345,
"Latitude": 321.332331
}"
Thanks :D Greatly appreciate your help!

Using JSON.parse seems to be the right approche.
But if you really want (for some reason) the regex solution, here it is:
var json = '{"CubicMillimeters": 3,"Longtitude": 342.152345, "Latitude": 321.332331 }',
reg = /"CubicMillimeters":\s*(.*?),/;
console.log(json.match(reg)[1]);
DEMO with explanation

Related

Javascript regex special character not working

I have a string:
for (;;); {
"__ar": 1,
"payload": null,
"jsmods": {
"require": [
["ServerRedirect", "redirectPageTo", [],
["https:\/\/bigzipfiles.facebook.com\/p\/dl\/download\/file.php?r=100028316830939&t=100028316830939&j=11&i=5823694&ext=12121516&hash=AaBVNURld6wrKBcU", true, false]
]
],
"define": [
["KSConfig", []
}
I try to regex this to be:
https://bigzipfiles.facebook.com/p/dl/download/file.php?r=100028316830939&t=100028316830939&j=11&i=5823694&ext=12121516&hash=AaBVNURld6wrKBcU
I've used
var results = $(document).find("pre").html();
var regex1 = new RegExp(/["\w\.\/\;\?\=\-\&\\\\"]/);
var resultsReplace = regex1.exec(results);
console.log(resultsReplace);
but it is not working.
Can anyone help me, please?
Assuming it is always URL and the delimiter is always " we can use a much simpler regex here, like:
str.match(/http[^"]+/)[0]
So we looking for a string starting with http with any following characters except " since the match string never can get one because this is a delimiter.
LMK if cases are wider (not an url, may not start with http, etc.) and I'll adjust regex.

How to parse a string, which is a list of ints into a list in Javascript? [duplicate]

This question already has answers here:
Convert JSON string to array of JSON objects in Javascript
(6 answers)
Closed 5 years ago.
I have a string which is a list of ints, and I need to parse it into a list of those ints. In other words, how to convert "[2017,7,18,9,0]" to [2017,7,18,9,0]?
more info
When i console.log(typeof [2017,7,18,9,0], [2017,7,18,9,0] ), I get: string [2017,7,18,9,0]. I need to convert it into a list such that doing console.log(), i get: object Array [ 2017, 7, 18, 9, 0 ].
Thanks in advance for any help!
You can use .match() with RegExp /\d+/, .map() with parameter Number
var res = "[2017,7,18,9,0]".match(/\d+/g).map(Number)
You can try parsing it as JSON:
console.log(JSON.parse("[2017,7,18,9,0]"))
Or you could try to manually parse the string:
var str = "[2017,7,18,9,0]";
str = str.substring(1, str.length - 1); // cut out the brackets
var list = str.split(",");
console.log(str);
var yourString = "[2017,7,18,9,0]";
var stringArray = JSON.parse(yourString);
console.log( JSON.stringify(stringArray), typeof stringArray);
Is it JSON.parse that you need?
By splitting with regex (because who doesn't love a regex):
var array = "[2017,7,18,9,0]".split(/\,|\[|\]/).shift().pop();
The shift and pop remove the empty strings from the front and back of the array, which are from the open and close brackets.
These solutions are turning into a list of every available option. So in that spirit I'll throw eval() into the mix.
eval("[2017, 23, 847, 4]");
NOTE: the other answers are much better and this method should not be used.
var strArray = "[2017, 23, 847, 4]";
var realArray = eval(strArray);
console.log(realArray);

regexp exactly matches with similar word

I have a pattern bellow:
var patt = /((name)|(names)*)/g;
and I have a string for match:
var word = "namesnames";
word is according to pattern logicly, but word.match(patt) return :
["name", "", "name", "", ""]
which is wrong!
i want "namesnames" result from match,
please help me.
thanks.
The problem is that you used (names)*, meaning "names" 0 or more times, when you should have done ((name)(?:s))+, meaning "name" or "names" 1 or more times.
If I understand what you want correctly, you can make it much simpler:
var patt = /(names?)+/g;

Regular Expression - Need help on getting specific part of a string

This is the stantard string structure:
{"actor":"100003221104984","target_fbid":"286108458103936","target_profile_id":"100003221104984","type_id":"17","source":"1","assoc_obj_id":"","source_app_id":"2305272732","extra_story_params":[],"content_timestamp":"1325711938","check_hash":"892251599922cc58"}
the only part i need from this string is the numeric value after the "target_profile_id", in this case, would be "100003221104984"
I really suck at regular expressions and any help would be really appreciated !
Thanks in advance
The data appears to be in JSON format (minus HTML escaped). As such, there is no need for a regular expression.
Instead, access it directly:
var data = {"actor":"100003221104984","target_fbid":"286108458103936", ...}
alert(data.target_profile_id);
See the fiddle.
UPDATE
As noted by Jonathan, if the string indeed includes HTML entities, you will need to first parse it to create an object to assign to data in my example above.
There are additional posts on SO that answer how to do that. For example: How to decode HTML entities using jQuery?
If you have all these &quo te; stuff you could also do it by getting the right chars, without regex
var x =
"{"actor":"100003221104984","target_fbid":"286108458103936","target_profile_id":"100003221104984","type_id":"17","source":"1","assoc_obj_id":"","source_app_id":"2305272732","extra_story_params":[],"content_timestamp":"1325711938","check_hash":"892251599922cc58"}";
var begin = x.indexOf("target_profile_id")+ "target_profile_id".length + "":"".length;
var endString = x.substring(begin, x.length);
var end = endString.indexOf(""") + begin;
alert(x.substring(begin, end));
Try:
/"actor":"(\[^&\]+)/
or
/"actor":"([^&]+)/
I have understood your problem. The whole string is actually a JSON object, where quote(") is present in the form of &quot ;.
First replace & quote; it with ". Then evaluate the expression and get the value of any item you want.
Below working code :)
<script type="text/javaScript">
var str1="{"actor":"100003221104984","target_fbid":"286108458103936","target_profile_id":"100003221104984","type_id":"17","source":"1","assoc_obj_id":"","source_app_id":"2305272732","extra_story_params":[],"content_ti":{"actor":"100003221104984","target_fbid":"286108458103936","target_profile_id":"100003221104984","type_id":"17","source":"1","assoc_obj_id":"","source_app_id":"2305272732","extra_story_params":[],"content_timestamp":"1325711938","check_hash":"892251599922cc58"}}";
var ans=str1.split(""").join("\"");
var obj=eval("(" + ans+ ')');
alert(obj.target_profile_id);
</script>
And see how your actual Data looks like:
{
"actor": "100003221104984",
"target_fbid": "286108458103936",
"target_profile_id": "100003221104984",
"type_id": "17",
"source": "1",
"assoc_obj_id": "",
"source_app_id": "2305272732",
"extra_story_params": [],
"content_ti": {
"actor": "100003221104984",
"target_fbid": "286108458103936",
"target_profile_id": "100003221104984",
"type_id": "17",
"source": "1",
"assoc_obj_id": "",
"source_app_id": "2305272732",
"extra_story_params": [],
"content_timestamp": "1325711938",
"check_hash": "892251599922cc58"
}
}

Change Link Into Keywords with Javascript

I wanna change the url text into a words, but have no idea to do that. Please help me.
Here's what I wanna do, example:
some-text-url.html
into
some text url
Use the split method:
var url = "some-text-url.html";
url = url.replace(".html", ""); // remove html
var words = url.split("-");
// words is now an array of the keywords
var str = "some-text-url.html";
str = str.split('.')[0].split('-').join(' ');
.split() on the . gives an Array of:
[
"some-text-url",
"html"
]
[0] gives the first string in the Array "some-text-url"
.split() on the - gives an Array of:
[
"some",
"text",
"url"
]
And .join() passing a string with a single space gives the final result:
"some text url"
Or here's another way to avoid creating an Array with .split():
var str = "some-text-url.html";
str = str.replace(/-|\.html$/g," ");
Giving you "some text url ".
Notice the space on the end. If you don't want that, add .slice(-1) after the .replace().

Categories