Javascript Regex replace specific string with specific constraints - javascript

I have a string like so: {{q:6}}
I need to be able to make a regex to take it and turn it into this:
"Question Here"
The Regex would need to ignore {{q: and would need to be [0-9] for any number from 0 to 100.
var final_value = value.replace(/^{{q:([0-9]+)$}}/g, 'question');
Using it in this context ^, but this isn't working. Any thoughts?
Thanks in advance!
EDIT:
Final working answer:
value.replace(/\{\{q:([0-9]+)\}\}/g, question);

String final_value = "{{q:6}}\n{{q:39}}".replaceAll("\\{\\{q:([0-9]+)\\}\\}", "Question: $1");
System.out.println(final_value);
This is java, a general answer would be: "/\{\{q:([0-9]+)\}\}/g"

The $ sign needs to go AFTER the }}
"{{q:6}}".replace(/^{{q:([0-9]+)}}$/g, 'question');// <= yields "question"

You need to escape your { and }.
Also if you want to limit from 0 to 100 inclusive, then you need to change:
[0-9]+
which will accept any string of digits to something like:
[1]?\d?\d
Which will accept 1 or not, a single digit (or not) and then a single digit.
Edit: and also #ruakh's comment about your placement of $ applies.

Related

Regex to extract two digits from phone number

I am trying to take only 2 characters from my phone no.
I have used regex match ^\+55 and this will return the following example.
Phone No : +5546342543
Result : 46342543
Expected Result was only 46.
I don't want to use substring for the answer instead I want to extract that from the phone no with regex.
Can anybody help me on this.
Thank you.
The pattern you used - ^\+55 - matches a literal + in the beginning of the string and two 5s right after.
46 is the substring that appears right after the initial +55. In some languages, you can use a look-behind (see example) to match some text preceded with another.
JavaScript has no look-behind support, so, you need to resort to capturing groups.
You can use string#match or RegExp#exec to obtain that captured text marked with round brackets:
var s = '+5546342543';
if ((m=/^\+55(\d{2})/.exec(s)) !== null) {
document.write(m[1]);
}
This example handles the case when you get no match.
Just try with:
'+5546342543'.match(/^\+55(\d{2})/)[1];
This will get what you want
"+5546342543".match(/^\+55(.*)/)[1]
This solves your problem ?
phoneNumber = "+5546342543"
phone = phoneNumber.substr(3) // returns "46342543"
twoDigits = phoneNumber.substr(3,2) // returns "46"
Using the substr() method as quoted :
The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.
Syntax: str.substr(start[, length])
Source : Mozilla MDN

pos or neg two-numbers in string match using regex

Why is it that this regex almost works to return an array of two strings that can be used as numbers, positive or negative, but the 2nd string has its negative sign dropped? I can think of workarounds for this using another line or two of code, but would really like to get the regex to do it right. Thanks in advance. (By the way, the idea here is that the string can be "123,321" or "12.3, 321" or "123 32.1" or any reasonable formatting of two reals or integers.)
s="-123.23, -456.0";
s.match(/^([+-]?\d*\.\d*)\W+([+-]?\d*.\d*)$/);
//-->["-123.23, -456.0", "-123.23", "456.0"]
Instead of trying to match the entire line, you might consider just matching the numbers ...
var r = "-123.23, -456.0".match(/[+-]?\d+(?:\.\d+)?/g);
console.log(r); //=> [ '-123.23', '-456.0' ]
Try: [^\w-]+ instead \W+
s = "-123.23, -456.0";
s.match(/^([+-]?\d*\.\d*)[^\w-]+([+-]?\d*.\d*)$/)

How can I get the last part of a songkick URL using regex?

I need to get the last part after the slash from this URL or even just the number using regex:
http://www.songkick.com/artists/2884896-netsky
Does anyone know how I can go about doing this?
Many thanks,
Joe
I've got a regex pattern to find everything after the last slash - it is ([^//]+)$ . Thanks!
don't know if this is ok for you:
last part:
"http://www.songkick.com/artists/2884896-netsky".replace(/.*\//,"")
"2884896-netsky"
number:
"http://www.songkick.com/artists/2884896-netsky".replace(/.*\//,"").match(/\d+/)
["2884896"]
Try this:
var s = "http://www.songkick.com/artists/2884896-netsky";
s.match(/[^\/]+$/)[0]
[^\/]+ matches one or more characters other than /
$ matches the end of the string
For just the number, try:
var value = s.match(/(\d+)[^\/\d]+$/)[1];
value = parseInt(value, 10); // convert it to an Integer
(\d+) matches any Number and groups it
[^\/\d]+ matches anything besides Numbers or /
More Info on Javascript Regular Expressions

How to allow whitespace in Regex

I have a regex which allows only to enter integers and floats in a text box.
Regex Code:-
("^[0-9]*(?:[.][0-9]*|)$");
But it gives an error when the user enters whitespace at the beginning and end of the entered values. I want the user to allow spaces at the beginning and at the end as optional, so I changed the regex as below but it didn't work.
Note: Spaces may be spaces or tabs.
Test Case: User might enter:
"10","10.23"," 10","10 "," 10.23","10.23 "
Any number of spaces are allowed.
("^(?:\s)*[0-9]*(?:[.][0-9]*|)$")
I am newbie with regex, so any help will be highly appreciated.
Thank you.
Try this:
/^\s*[0-9]*(?:[.][0-9]*|)\s*$/;
You don't have to wrap a single entity in a group to repeat it, and I have added a second zero-or-more-spaces at the end which is what you are missing to make it work.
Note: You have not posted the code you use to create the RegExp object, but if it is new RegExp(string), remember to escape your backslashes (by doubling them):
var r = new RegExp("^\\s*[0-9]*(?:[.][0-9]*|)\\s*$");
Also, as #Blender suggests, this can be simplified to:
/^\s*[0-9]*(?:\.[0-9]*)?\s*$/;
Or, using \d instead of [0-9]:
/^\s*\d*(?:\.\d*)?\s*$/;
You don't necessarily need a Regular Expression: !isNaN(Number(textboxvalue.trim())) would be sufficient.
Otherwise, try /^\s{0,}\d+\.{0,1}\d+\s{0,}$/. Test:
var testvalues = ["10","10.23"," 10","10 "," 10.23","10.23 ","10.24.25"];
for (var i=0;i<testvalues.length;i+=1){
console.log(/^\s{0,}\d+\.{0,1}\d+\s{0,}$/.test(testvalues[i]));
}
//=> 6 x true, 1 x false

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

Categories