Replacing text from regex match with jquery - javascript

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'?

Related

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

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);

jquery get value in brackets using regex

This has probably been asked a million times, and i am probably way off in what i have below, but i can not find it anywhere on SO. I need to get my alert below to show the value inside the brackets.
//the element(thisId) holds the following string: id[33]
var thisId = $(this).attr('id');
var idNum = new RegExp("\[(.*?)\]");
alert(idNum);
I need the alert to show the value 33.
You need to match the string with the regular expression, not just create the regexp. This returns an array containing the full match and the matches for capture groups.
var thisId = 'id[33]';
var match = thisId.match(/\[(.*?)\]/);
alert(match[1]); // Show first capture
You can use exec() to get the matches to your Regex:
var thisId = 'id[33]';
var matches = /\[(.*?)\]/g.exec(thisId);
alert(matches[1]); // you want the first group captured
Example fiddle

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")

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.

Javascript regExp - find brackets

I can't figure out how to search for a string containing something like "[1]", for some reason this doesn't work:
var regExp = '/\[[1-9]\]/';
var search = string.search(regExp); // returns -1
I've searched all over for a solution but can't find anything...
Try it without the '
var regExp = /\[[1-9]\]/;
var search = string.search(regExp);
I think it's the way you're actually attempting to match it. Try this:
string="something[1]";
if(string.match(/\[[1-9]\]/gi)) alert("Your string has brackets with a number inside!"); //Alerts correctly

Categories