how to get specific characters between others in a string with jquery? - javascript

Having a string such like this one:
var str = "https://www.portalinmobiliario.com/venta/departamento/vitacura-metropolitana/6579-parque-arboleda-nva";
I need to be able to only get "6579" number from that string, because it is an ID I need to use. In fact,
this ID is always located between that last "/" and the next "-" that follows.
So considering that the url is dynamic but this "ID" is always between these two characters "/" and "-", I have to be able to always get the ID.
Any Idea how could I solve this?
I tried with this but
var id = str.lastIndexOf('/');

You can use a regular expression to match digits, followed by a dash and making sure anything after it is not a slash.
var str = "https://www.portalinmobiliario.com/venta/departamento/vitacura-metropolitana/6579-parque-arboleda-nva";
console.log(str.match(/\/(\d+)-[^/]+$/)[1])

If you do not want to use a regexp.
'"https://www.portalinmobiliario.com/venta/departamento/vitacura-metropolitana/6579-parque-arboleda-nva"'
.split('/').pop()
.split('-').shift();
pop() removes the last element.
shift() removes the first element.

Take your var id and substr your original String
var index = str.lastIndexOf('/');
var id = str.substr(index+1,4);

Related

How to read only part of a string in Javascript

I am pulling in a string from another web page. I want to read that string into a variable but only after a certain point. Eg:
#stringexample
var variable;
I want variable to equal stringexample but not contain the # how could I do this?
This is how I am using the variable at the moment.
$("#Outputajax").load("folder/"+ variable +".html");
This is the way that works but isn't a variable.
$("#Outputajax").load("folder/webpage.html");
If you just want to trim of the first character, then you can use substring...
var input = "#stringexample";
input = input.substring(1);
//input = "stringexample"
Here is a working example
var myVariable = stringExample.replace('#','');
Could just use variable.substr(1) to cut off the first character.
If you want to specifically remove the hash from the start (but do nothing if the hash isn't there), try variable.replace(/^#/,"")
I understand you want to get everything in the string AFTER the hashtag. The other solutions will leave anything ahead of the hashtag in as well. And substring does not work if the hashtag is not the first symbol.
variable= "#stringexample".split("#")[1];
This splits the string into an array of strings, with the parameter as the point where to split, without including the parameter itself. There will be an empty string as the first parameter, and everything after the hashtag is the second string.
var slicer = function(somestring){
var parsedString = somestring;
parsedString = parsedString.slice(1);
return parsedString
}
// run from yors function with some string
var someYouVar = slicer("#something")

Matching the last digit or digits after a forward slash

In a JavaScript function in my Rails app, I'm trying to get the id of a recipe. Looking inside the event object like this
e.delegateTarget.baseURI
produces the uri, the last number of which (after the forward slash) is the id I want.
http://myroute.com/users/2/recipes/6
Of course, that id could be much longer in the future, so I need to be able to get all the digits after the last forward slash.
I tried to get the last id this way
var uri = e.delegateTarget.baseURI
var re = /^(.*[\\\/\d])/;
var recipe_id = uri.match(re);
The matched slash is supposed to be the last one because .* matches greedily, and then I look for any digit. This is all wrong. I'm not very experienced with regular expressions. Can you help?
A very simple way to do this would be to use string.split()
var uri = "http://myroute.com/users/2/recipes/6",
splituri = uri.split('/');
recipe_id = splituri[splituri.length - 1] // access the last index
Edit:
Even easier with the .pop() method, which returns the popped value
like elclanrs said.
var uri = e.delegateTarget.baseURI,
recipe_id = uri.split('/').pop();
You should use the special character $, which means end of input:
re = /\d+$/; //matches one or more digits from the end of the input
Here is a good resource on JavaScript regular expressions.

Get Second to last character position from string using jQuery

I have a dynamically formed string like - part1.abc.part2.abc.part3.abc
In this string I want to get the substring based on second to last occurrence of "." so that I can get and part3.abc
Is there any direct method available to get this?
You could use:
'part1.abc.part2.abc.part3.abc'.split('.').splice(-2).join('.'); // 'part3.abc'
You don't need jQuery for this.
Nothing to do with jQuery. You can use a regular expression:
var re = /[^\.]+\.[^\.]+$/;
var match = s.match(re);
if (match) {
alert(match[0]);
}
or
'part1.abc.part2.abc.part3.abc'.match(/[^.]+\.[^.]+$/)[0];
but the first is more robust.
You could also use split and get the last two elements from the resulting array (if they exist).

Finding image url via using Regex

Any working Regex to find image url ?
Example :
var reg = /^url\(|url\(".*"\)|\)$/;
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)';
console.log(string.match(reg));
console.log(string2.match(reg));
I tied but fail with this reg
pattern will look like this, I just want image url between url(" ") or url( )
I just want to get output like http://domain.com/randompath/random4509324041123213.jpg
http://jsbin.com/ahewaq/1/edit
I'd simply use this expression:
/url.*\("?([^")]+)/
This returns an array, where the first index (0) contains the entire match, the second will be the url itself, like so:
'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1];
//returns "http://domain.com/randompath/random4509324041123213.jpg"
//or without the quotes, same return, same expression
'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1];
If there is a change that single and double quotes are used, you can simply replace all " by either '" or ['"], in this case:
/url.*\(["']?([^"')]+)/
Try this regexp:
var regex = /\burl\(\"?(.*?)\"?\)/;
var match = regex.exec(string);
console.log(match[1]);
The URL is captured in the first subgroup.
If the string will always be consistent, one option would be simply to remove the first 4 characters url(" and the last two "):
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
// Remove last two characters
string = string.substr(0, string.length - 2);
// Remove first five characters
string = string.substr(5, string.length);
Here's a working fiddle.
Benefit of this approach: You can edit it yourself, without asking StackOverflow to do it for you. RegEx is great, but if you don't know it, peppering your code with it makes for a frustrating refactor.

Replacing text from regex match with jquery

This is driving me crazy, what is the reason this doesn't work?
var name = data.match(/first-([A-Za-z0-9-]+)/g).replace('first-', '');
I want to replace first-joe with joe.
I also tried
var name = data.match(/first-([A-Za-z0-9-]+)/g);
var name = name.replace('first-', '');
and that doesn't work.
However the when alerting name I get first-joe
What is the reason for this, and how do I fix it?
Thanks
Try this instead:
var name = data.replace(/first-([A-Za-z0-9-]+)/g, '$1');
match with /g returns an array of matches (excluding parenthesized substrings), so you would have to replace them individually. If you know there is exactly one match, use data.match(/first-([A-Za-z0-9-]+)/)[1] which extracts the parenthesized substring.
I'm not sure why you're calling match first. Why not simply do either of these?
var name1 = data.replace('first-', '');
var name2 = data.replace(/^first-/, ''); //In case somebodys got a name containing first-.
Is it because your data variable contains something more than the string 'first-joe'?

Categories