Javascript regular expression adjustment - javascript

Using mootools I have a regex like this:
new RegExp('^([^\\D'+ separator +']+)(\\d{2})');
In a string it inserts the char defined in separator after every 2 characters. I want it to insert only for the last two.
Example:
String Result
123456 12.34.56 // what it does now
123456 1234.56 // what it should do
I don't have much experience with regex so any help or link to a decent tutorial is appreciated.

If your string only consists of digits, isn't this the same as divide by 100?
'' + str / 100
It might depend on locale though ;-)
I can improve this answer if you have more edge cases I can work with.
If you absolutely must just regular expressions, you could always use this:
'123456'.replace(/(.)(\d{2})$/, function($0, $1, $2) {
return $1 + '.' + $2;
});
This would protect you against strings that would otherwise result in NaN, such as 'foo'.

Don't use regex for this:
var str = "123456".split('').reverse().join('');
var x = str.substring(0,2) + '.' + str.substring(2);
var final = x.split('').reverse().join('');
console.log(final);
Live DEMO
Of course you can check if the string length is bigger than 2
if (str.length > 2)
// ...
Or use string slice function:
str ="123456";
str.slice(0, -2) + "." + str.slice(-2);
How does it work?
I'll break it into pieces:
// Start at the beginning of the string grab all the chars
// and stop two chars before the end of the string
str.slice(0, -2)
// Start at two chars before the end of the string, take all the chars until
// the end of the string.
str.slice(-2);

Assume the string always has more than 2 characters:
str.slice(0, -2) + "." + str.slice(-2)
Reference to String.slice.

Related

Regex match cookie value and remove hyphens

I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens. I would like to replace the hyphens with a space and set to a variable. Javascript or jQuery.
As an example, the larger string has a name and value like this within it:
facility=34222%7CConner-Department-Store;
(notice the leading "C")
So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex. Then break it down to "Conner Department Store"
var cookie = document.cookie;
var facilityValue = cookie.match( REGEX ); ??
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";
var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
return decodeURIComponent(match2);
});
console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.
This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Demo:
var str = "facility=34222%7CConner-Department-Store;";
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Explanation:
Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.
Replace any - occurence in the matched words.
Then just join these matches array with white space.
Ok,
first, you should decode this string as follows:
var str = "facility=34222%7CConner-Department-Store;"
var decoded = decodeURIComponent(str);
// decoded = "facility=34222|Conner-Department-Store;"
Then you have multiple possibilities to split up this string.
The easiest way is to use substring()
var solution1 = decoded.substring(decoded.indexOf('|') + 1, decoded.length)
// solution1 = "Conner-Department-Store;"
solution1 = solution1.replace('-', ' ');
// solution1 = "Conner Department Store;"
As you can see, substring(arg1, arg2) returns the string, starting at index arg1 and ending at index arg2. See Full Documentation here
If you want to cut the last ; just set decoded.length - 1 as arg2 in the snippet above.
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1)
//returns "Conner-Department-Store"
or all above in just one line:
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1).replace('-', ' ')
If you want still to use a regular Expression to retrieve (perhaps more) data out of the string, you could use something similar to this snippet:
var solution2 = "";
var regEx= /([A-Za-z]*)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/;
if (regEx.test(decoded)) {
solution2 = decoded.match(regEx);
/* returns
[0:"facility=34222|Conner-Department-Store",
1:"facility",
2:"34222",
3:"Conner-Department-Store",
index:0,
input:"facility=34222|Conner-Department-Store;"
length:4] */
solution2 = solution2[3].replace('-', ' ');
// "Conner Department Store"
}
I have applied some rules for the regex to work, feel free to modify them according your needs.
facility can be any Word built with alphabetical characters lower and uppercase (no other chars) at any length
= needs to be the char =
34222 can be any number but no other characters
| needs to be the char |
Conner-Department-Store can be any characters except one of the following (reserved delimiters): :/?#[]#;,'
Hope this helps :)
edit: to find only the part
facility=34222%7CConner-Department-Store; just modify the regex to
match facility= instead of ([A-z]*)=:
/(facility)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).
Simply include the cookies.js file in your application, and write:
docCookies.getItem("Connor Department Store");

match numbers without a prefix

I need help with regular expression.
Using javascript I am going through each line of a text file and I want to replace any match of [0-9]{6,9} with a '*', but, I don't want to replace numbers with prefix 100. So, a number like 1110022 should be replaced (matched), but 1004567 should not (no match).
I need a single expression that will do the trick (just the matching part). I can’t use ^ or $ because the number can appear in the middle of the line.
I have tried (?!100)[0-9]{6,9}, but it doesn't work.
More examples:
Don't match: 10012345
Match: 1045677
Don't match:
1004567
Don't match: num="10034567" test
Match just the middle number in the line: num="10048876" 1200476, 1008888
Thanks
You need to use a leading word boundary to check if a number starts with some specific digit sequence:
\b(?!100)\d{6,9}
See the regex demo
Here, the 100 is checked right after a word boundary, not inside a number.
If you need to replace the matches with just a single asterisk, just use the "*" as a replacement string (see snippet right below).
var re = /\b(?!100)\d{6,9}/g;
var str = 'Don\'t match: 10012345\n\nMatch: 1045677\n\nDon\'t match:\n\n1004567\n\nDon\'t match: num="10034567" test\n\nMatch just the middle number in the line: num="10048876" 1200476, 1008888';
document.getElementById("r").innerHTML = "<pre>" + str.replace(re, '*') + "</pre>";
<div id="r"/>
Or, if you need to replace each digit with *, you need to use a callback function inside a replace:
String.prototype.repeat = function (n, d) {
return --n ? this + (d || '') + this.repeat(n, d) : '' + this
};
var re = /\b(?!100)\d{6,9}/g;
var str = '123456789012 \nDon\'t match: 10012345\n\nMatch: 1045677\n\nDon\'t match:\n\n1004567\n\nDon\'t match: num="10034567" test\n\nMatch just the middle number in the line: num="10048876" 1200476, 1008888';
document.getElementById("r").innerHTML = "<pre>" + str.replace(re, function(m) { return "*".repeat(m.length); }) + "</pre>";
<div id="r"/>
The repeat function is borrowed from BitOfUniverse's answer.

Regex to replace all but the last non-breaking space if multiple words are joined?

Using javascript (including jQuery), I’m trying to replace all but the last non-breaking space if multiple words are joined.
For example:
Replace A String of Words with A String of Words
I think you want something like this,
> "A String of Words".replace(/ (?=.*? )/g, " ")
'A String of Words'
The above regex would match all the   strings except the last one.
Assuming your string is like this, you can use Negative Lookahead to do this.
var r = 'A String of Words'.replace(/ (?![^&]*$)/g, ' ');
//=> "A String of Words"
Alternative to regex, easier to understand:
var fn = function(input, sep) {
var parts = input.split(sep);
var last = parts.pop();
return parts.join(" ") + sep + last;
};
> fn("A String of Words", " ")
"A String of Words"

RegEx needed to split javascript string on "|" but not "\|"

We would like to split a string on instances of the pipe character |, but not if that character is preceded by an escape character, e.g. \|.
ex we would like to see the following string split into the following components
1|2|3\|4|5
1
2
3\|4
5
I'm expecting to be able to use the following javascript function, split, which takes a regular expression. What regex would I pass to split? We are cross platform and would like to support current and previous versions (1 version back) of IE, FF, and Chrome if possible.
Instead of a split, do a global match (the same way a lexical analyzer would):
match anything other than \\ or |
or match any escaped char
Something like this:
var str = "1|2|3\\|4|5";
var matches = str.match(/([^\\|]|\\.)+/g);
A quick explanation: ([^\\|]|\\.) matches either any character except '\' and '|' (pattern: [^\\|]) or (pattern: |) it matches any escaped character (pattern: \\.). The + after it tells it to match the previous once or more: the pattern ([^\\|]|\\.) will therefor be matches once or more. The g at the end of the regex literal tells the JavaScript regex engine to match the pattern globally instead of matching it just once.
What you're looking for is a "negative look-behind matching regular expression".
This isn't pretty, but it should split the list for you:
var output = input.replace(/(\\)?|/g, function($0,$1){ return $1?$1:$0+'\n';});
This will take your input string and replace all of the '|' characters NOT immediately preceded by a '\' character and replace them with '\n' characters.
A regex solution was posted as I was looking into this. So I just went ahead and wrote one without it. I did some simple benchmarks and it is -slightly- faster (I expected it to be slower...).
Without using Regex, if I understood what you desire, this should do the job:
function doSplit(input) {
var output = [];
var currPos = 0,
prevPos = -1;
while ((currPos = input.indexOf('|', currPos + 1)) != -1) {
if (input[currPos-1] == "\\") continue;
var recollect = input.substr(prevPos + 1, currPos - prevPos - 1);
prevPos = currPos;
output.push(recollect);
}
var recollect = input.substr(prevPos + 1);
output.push(recollect);
return output;
}
doSplit('1|2|3\\|4|5'); //returns [ '1', '2', '3\\|4', '5' ]

filter out a percentage from a string using a regular expression in javascript

I have the following string value: £-155 (-2.2%)
Out of that I want to be able to extract anything that is a number and may/may not contain a '-' minus sign. so the above would be: -2.2
I also need to know whether the value has a percentage in the form as above or not...a conditional statement will be used in the final code.
thoughts?
Why use regex for something so simple? Why not just grab the last character in the string and check if it's a digit or a %.
Likewise, if you want to remove it, just drop the last character from the string using the .substr() method:
http://www.w3schools.com/jsref/jsref_substr.asp
You basically want a regex that matches a number, which has been answered many times before.
Then once you have that, just add an optional percent symbol (%?) and check for its presence in the matched string.
// An optional sign and either an integer followed by an optional fraction
// or a decimal fraction.
var numberRe = '[+-]?(?:[0-9]+(?:[.][0-9]*)?|[.][0-9]+)';
// Matches a number (in group 1)
// and an optional percentage in parentheses (in group 2).
var quantity = new RegExp(
'(' + numberRe + ')(?:\\s*[(]\\s*(' + numberRe + ')\\s*%\\s*[)])?');
If you match with quantity you should get the number in group 1 and any percentage in group 2.
JSON.stringify(quantity.exec('£-155 (-2.2%)'))
["-155 (-2.2%)", "-155", "-2.2"]
To get them as numbers, use parseFloat or unary + as in
var match = quantity.exec('£-155 (-2.2%)');
var n = +match[1], pct = match[2] != null ? +match[2] / 100 : NaN;
alert('n = ' + n + ', whole = ' + (pct ? n / pct : "unknown"));

Categories

Resources