Help with a regular expression to capture numbers - javascript

I need to capture the price out of the following string:
Price: 30.
I need the 30 here, so I figured I'd use the following regex:
([0-9]+)$
This works in Rubular, but it returns null when I try it in my javascript.
console.log(values[1]);
// Price: 100
var price = values[1].match('/([0-9]+)$/g');
// null
Any ideas? Thanks in advance

Try this:
var price = values[1].match(/([0-9]+)$/g);
JavaScript supports RegExp literals, you don't need quotes and delimiters.
.match(/\d+$/) should behave the same, by the way.
See also: MDN - Creating a Regular Expression
Keep in mind there are simpler ways of getting this data. For example:
var tokens = values[1].split(': ');
var price = tokens[1];
You can also split by a single space, and probably want to add some validation.

Why don't you use this?
var matches = a.match(/\d+/);
then you can consume the first element (or last)
my suggestion is to avoid using $ in the end because there might be a space in the end.

This also works:
var price = values[1].match('([0-9]+)$');

It appears that you escaped the open-perens and therefore the regex is looking for "(90".

You don't need to put quotes around the regular expression in JavaScript.

Related

jQuery / Javascript replace multiple occurences not working

I'm trying to replace multiple occurrences of a string and nothing seems to be working for me. In my browser or even when testing online. Where am I going wrong?
str = '[{name}] is happy today as data-name="[{name}]" won the match today. [{name}] made 100 runs.';
str = str.replace('/[{name}]/gi','John');
console.log(str);
http://jsfiddle.net/SXTd4/
I got that example from here, and that too wont work.
You must not quote regexes, the correct notation would be:
str = str.replace(/\[{name}\]/gi,'John');
Also, you have to escape the [], because otherwise the content inside is treated as character class.
Updating your fiddle accordingly makes it work.
There are two ways declaring regexes:
// literal notation - the preferred option
var re = /regex here/;
// via constructor
var re = new Regexp('regex here');
You should not put your regex in quotes and you need to escape []
Simply use
str = str.replace(/\[{name}\]/gi,'John');
DEMO
While there are plenty of regex answers here is another way:
str = str.split('[{name}]').join('John');
The characters [ ] { } should be escaped in your regular expression.

how to replace strings before another string

I have this string:
var str = "jquery12325365345423545423im-a-very-good-string";
What I would like to do, is removing the part 'jquery12325365345423545423' from the above string.
The output should be:
var str = 'im-a-very-good-string';
How can I remove that part of the string using php? Are there any functions in php to remove a specified part of a string?
sorry for not including the part i have done
I am looking for solution in js or jquery
so far i have tried
var str="jquery12325365345423545423im-a-very-good-string";
str=str.replace("jquery12325365345423545423","");
but problem is numbers are randomly generated and changed every time.
so is there other ways to solve this using jquery or JS
The simplest solution is to do it with:
str = str.replace(/jquery\d+/, '').replace(' ', '');
You can use string replace.
var str = "jquery12325365345423545423im-a-very-good-string";
str.replace('jquery12325365345423545423','');
Then to removespaces you can add this.
str.replace(' ','');
I think it will be best to describe the methods usually used with this kind of problems and let you decide what to use (how the string changes is rather unclear).
METHOD 1: Regular expression
You can search for a regular expression and replace the part of the string that matches the regular expression. This can be achieved through the JavaScript Replace() method.
In your case you could use following Regular expression: /jquery\d+/g (all strings that begin with jquery and continue with numbers, f.e. jquery12325365345423545423 or jquery0)
As code:
var str="jquery12325365345423545423im-a-very-good-string";
str=str.replace("/jquery\d+/g","");
See the jsFiddle example
METHOD 2: Substring
If your code will always have the same length and be at the same position, you should probably be using the JavaScript substring() method.
As code:
var str="jquery12325365345423545423im-a-very-good-string";
var code = str.substring(0,26);
str=str.substring(26);
See the jsFiddle example
Run this sample in chrome dev tools
var str="jquery12325365345423545423im-a-very-good-string";
str=str.replace("jquery12325365345423545423","");
console.log(str)

Javascript regex expression to replace multiple strings?

I've a string done like this: "http://something.org/dom/My_happy_dog_%28is%29cool!"
How can I remove all the initial domain, the multiple underscore and the percentage stuff?
For now I'm just doing some multiple replace, like
str = str.replace("http://something.org/dom/","");
str = str.replace("_%28"," ");
and go on, but it's really ugly.. any help?
Thanks!
EDIT:
the exact input would be "My happy dog is cool!" so I would like to get rid of the initial address and remove the underscores and percentage and put the spaces in the right place!
The problem is that trying to put a regex on Chrome "something goes wrong". Is it a problem of Chrome or my regex?
I'd suggest:
var str = "http://something.org/dom/My_happy_dog_%28is%29cool!";
str.substring(str.lastIndexOf('/')+1).replace(/(_)|(%\d{2,})/g,' ');
JS Fiddle demo.
The reason I took this approach is that RegEx is fairly expensive, and is often tricky to fine tune to the point where edge-cases become less troublesome; so I opted to use simple string manipulation to reduce the RegEx work.
Effectively the above creates a substring of the given str variable, from the index point of the lastIndexOf('/') (which does exactly what you'd expect) and adding 1 to that so the substring is from the point after the / not before it.
The regex: (_) matches the underscores, the | just serves as an or operator and the (%\d{2,}) serves to match digit characters that occur twice in succession and follow a % sign.
The parentheses surrounding each part of the regex around the |, serve to identify matching groups, which are used to identify what parts should be replaced by the ' ' (single-space) string in the second of the arguments passed to replace().
References:
lastIndexOf().
replace().
substring().
You can use unescape to decode the percentages:
str = unescape("http://something.org/dom/My_happy_dog_%28is%29cool!")
str = str.replace("http://something.org/dom/","");
Maybe you could use a regular expression to pull out what you need, rather than getting rid of what you don't want. What is it you are trying to keep?
You can also chain them together as in:
str.replace("http://something.org/dom/", "").replace("something else", "");
You haven't defined the problem very exactly. To get rid of all stretches of characters ending in %<digit><digit> you'd say
var re = /.*%\d\d/g;
var str = str.replace(re, "");
ok, if you want to replace all that stuff I think that you would need something like this:
/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g
test
var string = "http://something.org/dom/My_happy_dog_%28is%29cool!";
string = string.replace(/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g,"");

Extract text from HTML with Javascript regex

I am trying to parse a webpage and to get the number reference after <li>YM#. For example I need to get 1234-234234 in a variable from the HTML that contains
<li>YM# 1234-234234 </li>
Many thanks for your help someone!
Rich
currently, your regex only matches if there is a single number before the dash and a single number after it. This will let you get one or more numbers in each place instead:
/YM#[0-9]+-[0-9]+/g
Then, you also need to capture it, so we use a cgroup to captue it:
/YM#([0-9]+-[0-9]+)/g
Then we need to refer to the capture group again, so we use the following code instead of the String.match
var regex = /YM#([0-9]+-[0-9]+)/g;
var match = regex.exec(text);
var id = match[1];
// 0: match of entire regex
// after that, each of the groups gets a number
(?!<li>YM#\s)([\d-]+)
http://regexr.com?30ng5
This will match the numbers.
Try this:
(<li>[^#<>]*?# *)([\d\-]+)\b
and get the result in $2.

Javascript Regex after specific string

I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with 'ajax-', and ending with a name. For instance 'ajax-first', 'ajax-last', 'ajax-email', etc.
How can I make a regex to only grab the string after 'ajax-'?
So instead of 'ajax-email', I want just 'email'.
You don't need RegEx for this. If your prefix is always "ajax-" then you just can do this:
var name = string.substring(5);
Given a comment you made on another user's post, try the following:
var $li = jQuery(this).parents('li').get(0);
var ajaxName = $li.className.match(/(?:^|\s)ajax-(.*?)(?:$|\s)/)[1];
Demo can be found here
Below kept for reference only
var ajaxName = 'ajax-first'.match(/(\w+)$/)[0];
alert(ajaxName);
Use the \w (word) pattern and bind it to the end of the string. This will force a grab of everything past the last hyphen (assuming the value consists of only [upper/lower]case letters, numbers or an underscore).
The non-regex approach could also use the String.split method, coupled with Array.pop.
var parts = 'ajax-first'.split('-');
var ajaxName = parts.pop();
alert(ajaxName);
you can try to replace ajax- with ""
I like the split method #Brad Christie mentions, but I would just do
function getLastPart(str,delimiter) {
return str.split(delimiter)[1];
}
This works if you will always have only two-part strings separated by a hyphen. If you wanted to generalize it for any particular piece of a multiple-hyphenated string, you would need to write a more involved function that included an index, but then you'd have to check for out of bounds errors, etc.

Categories