How to get value from string with lodash? - javascript

Suppose I have a url that looks like this:
http://mysite/super/id/800
The 'super/id' part in the URL is fixed.I am trying to create a compact statement to return the 800 value with lodash. What could be a solution for this. I know how to split it up into an array and then get it from there but just looking for a more elegant solution?

Although it's not lodash I would argue that given the 800 portion of the string is certain to be the final part, the following is cleanest.
string.split('/').pop();
It's best (in my opinion) to avoid using frameworks and libraries unless there is a deficit in the language requiring you to do so.

If you want to avoid creating an array, you could try using String#slice and String#lastIndexOf:
var string = 'http://mysite/super/id/800'
console.log(
string.slice(string.lastIndexOf('/') + 1) //=> '800'
)

Try Regular Expressions
Your url seems to be a good candidate.
var url = "http://mysite/super/id/800";
var pattern = /\d+$/;
var match = pattern.exec(url);
// ["800"], it will be null if there was no match

Related

Extract value from location hash

In the front-end Javascript code, I need to extract a value from the location hash parameter.
For example, the url looks like:
https://mywebsite.com/certainpage#comment-12345
Here, I want to extract the value 12345 which indicates the id of comment. Currently, I am using the following code to do it:
const match = window.location.hash.match(/-([0-9]*)/) || [];
if (!match[1]) return;
// Use match[1]
If there is any optimized and clean way to handle this, please let me know.
If it's always #comment-NUM, then you don't even need to go for RegEx.
const match = window.location.hash.split("-") || [];
Then the same checks will apply. Use match[1] going forward. The reason is, String.split is better in performance than String.match. Also, it looks lot cleaner too.

Find and replace regex JavaScript

I know this is a super easy question, but I can't seem to wrap my head about it. I've got a bunch of URLs in varying languages such as:
www.myurl.com?lang=spa
www.myurl.com?lang=deu
www.myurl.com?lang=por
I need to create buttons to quickly switch from any language extension (spa, por, deu, rus, ukr, etc) to another language. I have the following code so far:
var url = window.location.toString();
window.location = url.replace(/lang=xxx/, 'lang=deu');
I just can't figure out the 3-character wildcard character. I know that I need to do some sort of regular expression or something, I'm just not sure how to go about it. Any help?
Thanks in advance
You can use
([&?]lang=)\w+
This will work with urls like www.myurl.com?foo=bar&lang=por&bar=foo too.
Instead of lang=deu, you'll have to replace with $1deu.
Try ... or .{3} or \w{3} or even [a-z]{3}, depending on how specific you want to be.
var s = 'www.myurl.com?lang=spa';
s.replace(/lang=[a-z]{3}/, 'lang=deu');
// => "www.myurl.com?lang=deu"
Here's a railroad diagram of the above example:
Use /lang=[a-z][3}/, here's an example:
/lang=[a-z]{3}/
Debuggex Demo

How to Split many Strings with Jquery

Let's say I have a bunch of strings which I get from user input. Each strings starts with a new line like the following example:
gordon:davis
harley:vona
empir:domen
furno:shyko
I would like to write a function in jQuery which loads the user data from the form and splits each row's sting. However I would ONLY need the first part of the strings, like:
gordon
harley
empir
furno
Is there any simple solution for this?
I have found something called: $.each(split) but I didn't get it work.
I'm sorry I'm a really newbie in Jquery, I hope you guys can help me out! Thanks in advance!
Use String.prototype.split method.
"gordon:davis".split(":") will return ["gordon","davis"]
Based on this, using Array.prototype.map or a JQuery version :
var strings = ["gordon:davis", "harley:vona"];
var splitStrings = strings.map(function (string) {
return string.split(":")[0];
});

How to parse JavaScript using Nokogiri and Ruby

I need to parse an array out of a website. The part of the JavaScript I want to parse looks like this:
_arPic[0] = "http://example.org/image1.jpg";
_arPic[1] = "http://example.org/image2.jpg";
_arPic[2] = "http://example.org/image3.jpg";
_arPic[3] = "http://example.org/image4.jpg";
_arPic[4] = "http://example.org/image5.jpg";
_arPic[5] = "http://example.org/image6.jpg";
I get the whole JavaScript using something like this:
product_page = Nokogiri::HTML(open(full_url))
product_page.css("div#main_column script")[0]
Is there an easy way to parse all the variables?
If I read you correctly you're trying to parse the JavaScript and get a Ruby array with your image URLs yes?
Nokogiri only parses HTML/XML so you're going to need a different library; A cursory search turns up the RKelly library which has a parse function that takes a JavaScript string and returns a parse tree.
Once you have a parse tree you're going to need to traverse it and find the nodes of interest by name (e.g. _arPic) then get the string content on the other side of the assignment.
Alternatively, if it doesn't have to be too robust (and it wouldn't be) you can just use a regex to search the JavaScript if possible:
/^\s*_arPic\[\d\] = "(.+)";$/
might be a good starter regex.
The easy way:
_arPic = URI.extract product_page.css("div#main_column script")[0].text
which can be shortened to:
_arPic = URI.extract product_page.at("div#main_column script").text

How to get an Id out of a Url client side?

If I have a URl like "/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d" what would be the best way to get the ID "2c02ds92-25cb-43e1-9bba-3bd5604a0a3d" out of the URL client side?
I need to be able to build a $.getJSON request with the ID and I'm looking for the cleanest way to do it using JavaScript, jQuery, etc. Thanks
$.getJSON('/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d')...
Use regular expressions and extract the appropriate part (which seems to be UUID) from the URL.
The alternative is to just split the string by / and get last element.
EDIT: The example on how to retrieve UUID from the URI:
var url = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d';
var pattern = /[\da-f]{8}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{12}/;
var match = url.match(pattern)[0];
url.match(pattern) returns array of matches, so assuming there is at least one, and only one match, you should pick it (using [0], as in the example).
Proof: http://jsfiddle.net/p6zud/2/
EDIT 2: Shortened the pattern used for matching (see revision history for comparison).
If the id is always going to be the last section of the URI, you could do something like
var url_array = document.location.split('/');
var id = url_array[url_array.length - 1];
using split, convert the url to an array of parameters. Then last array item in your case would be your ID.
there are very sophisticated URL parsers out there for javascript, perhaps you should look around on google for one that suits your needs.
The simpliest:
var id = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d'.split('/User/')[1];
Gives you 2c021192-25cb-43e1-9bba-3bd5604a0a3d;
Try this
alert("/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d".split('/').slice(-1)[0]);

Categories

Resources