Jquery check if special char exists in text value - javascript

i need to check if a textarea contains some special characters, so i need to count them 2 (SMS lenght).
I wrote this piece of code but seems that it doesn't find no special chars, also if write only "€€€"
Could you please help me? Also if you would to rewrite directly function, without problem. Thank tou!
var SPECIAL_CHARS = Array('€', '%');
function charUsed() {
var count = $('#text').val().length;
var chars = $('#text').val().split("");
var numberOfSpecialChars = 0;
if ($.inArray(chars, SPECIAL_CHARS) > -1) {
numberOfSpecialChars++;
}
return count + numberOfSpecialChars;
} // function

A rewrite :
var nbSpecialChars = $('#text').val().split(/[€%]/).length - 1;
The idea is to make an array of strings, using your special characters as separator :
'some € chars %' => ["some ", " chars ", ""]
and then use the length of this array to deduce the count of those chars. There are many other (faster) solutions but this one is short.

http://jsfiddle.net/KSm7J/
var chars = $('#text').val().match(/[€%]/g).length;
alert(chars);

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

Replace string with condition in google script

in google script I am trying to replace a %string basing on the character following it.
I've tried using:
var indexOfPercent = newString.indexOf("%");
and then check the character of indexOfPercent+1, but indexOf returns only the first occurrence of '%'.
How can I get all occurrences? Maybe there is easier way to do that (regular expressions)?
EDIT:
Finally I want to replace all my % occurrences to %%, but not if percent sign was part of %# or %#.
To sum up: my string: Test%# Test2%s Test3%. should look like: Test%# Test2%s Test3%%.
I've tried using something like this:
//?!n Matches any string that is not followed by a specific string n
//(x|y) Find any of the alternatives specified
var newString = newString.replace(\%?![s]|\%?![%], "%%")
but it didn't find any strings. I am not familiar with regex's, so maybe it is a simple mistake.
Thanks
Try this code:
// replace all '%'
var StrPercent = '%100%ffff%';
var StrNoPersent = StrPercent.replace(/\%/g,'');
Logger.log(StrNoPersent); // 100ffff
Look for more info here
Edit
In your case you need RegEx with the character not followed by group of characters. Similiar question was asked here:
Regular expressions - how to match the character '<' not followed by ('a' or 'em' or 'strong')?
Thy this code:
function RegexNotFollowedBy() {
var sample = ['Test%#',
'Test2%s',
'Test3%',
'%Test4%'];
var RegEx = /%(?!s|#)/g;
var Replace = "%%";
var str, newStr;
for (var i = 0; i < sample.length; i++) {
str = sample[i];
newStr = str.replace(RegEx, Replace);
Logger.log(newStr);
}
}
I'll explain expression /%(?!s|#)/g:
% -- look '%'
(text1|text2|text3...|textN) -- not followed by text1, 2 etc.
g -- look for any accurance of searched text

get only number from value and calculate the length from text field

I HAVE A TEXT FIELD
<input id="prime-phone" class="number-format" name="prime-phone" placeholder="" type="tel">
and there if fix value and it would be "(432)432-2432".
I want to count the length of number only not the special character like "(" , "-"
I am trying in this way and i also know i am doing somthing wrong
sd = $(".number-format").val();
alert(sd);
sd = parseInt(sd)
alert(sd)
number format can be change like "(432)432-2432" , "(43)-(432)-2432"
Thanks
in advance for the help :)
var sd = $(".number-format").val();
//i want to count the length of number only not the special character like "(" , "-"
var len = sd.match(/\d/g).length;
try it
Use regex to match the digits and count:
sd.match(/\d/g).length
Remove non digit character using replace() and count
sd=$(".number-format").val();
alert(sd);
len=sd.replace(/\D/g,'').length;
// \D used to match all non-digit character
alert(len);
DEMO
A reusable solution.
once defined you could just call them to exclude the unwanted characters and get the length.i find this easier to maintain.
var tel = "(432)432-2432";
var getLength = function(tel){
var telStr = tel.split('');
var excpetionList = ['(',')','-']; //<-- here you can add the chars to remove
return telStr.filter(function(item,index,arr){
if(excpetionList.indexOf(item) < 0){
return item;
}
}).join('').length;
};
console.log(getLength(tel));
demo

What's the exact regex to match the proper string?

My string has [1212,1212],[1212,11212],...
I'd like to extract each value into an array for example I'd want 1212,1212 as one pair and evaluate a series of steps.
Tried /[[0-9],[0-9]]/ but It wasn't doing the task as I wanted. Basically I'm a noob in Regex, could someone please help.
Thanks in advance
You need some modifications for your regular expression for it to work correctly:
/\[[0-9]+,[0-9]+\]/g
You need to escape square brackets [ because they have special meaning.
[0-9] matches only one digits, you need the + quantifier to match one or more digits and thus [0-9]+.
Use the global modifier g to extract all matches.
Then you can extract all the values into an array like this:
var input = "[1212,1212],[1212,11212]";
var pattern = /\[[0-9]+,[0-9]+\]/g;
var result = [];
var currentMatch;
while((currentMatch = pattern.exec(input)) != null) {
result.push(currentMatch.toString());
}
result;
Or if you don't need to find the matches successively one at a time, then you can use String.match() as #Matthew Mcveigh did:
var input = "[1212,1212],[1212,11212]";
var result = input.match(/\[[0-9]+,[0-9]+\]/g);
It seems like you just need to match one or more digits before and after a comma, so you could do the following:
"[1212,1212],[1212,11212]".match(/\d+,\d+/g)
Which will give you the array: ["1212,1212", "1212,11212"]
To extract the pairs:
var result = "[1212,1212],[1212,11212]".match(/\d+,\d+/g);
for (var i = 0; i < result.length; i++) {
var pair = result[i].match(/\d+/g),
left = pair[0], right = pair[1];
alert("left: " + left + ", right: " + right);
}
You need to escape the literal brackets that you want to match. You can also use \d to match "any digit", which makes it tidier. Also, you're only matching one digit. You need to match "one or more" (+ quantifier)
/\[\d+,\d+\]/g
That g modifier finds all matches in the string, otherwise only the first one is found.

How to match with javascript and regex?

I have the following HTML:
<span id="UnitCost5">$3,079.95 to $3,479.95</span>
And i want to use Javascript and Regex to get all number matches.
So i want my script function to return: 3,079.95 AND 3,479.95
Note the text may be different so i need the solution as generic as posible, may be it will be like this:
<span id="UnitCost5">$3,079.95 And Price $3,479.95</span>
All the numbers would be matched by:
\.?\d[\d.,]*
This assumes the numbers you look for can start with a decimal dot. If they cannot, this would work (and maybe produce less false positives):
\d[\d.,]*
Be aware that different local customs exist in number formatting.
I assume that you use appropriate means to get hold of the text value of the HTML nodes you wish to process, and that HTML parsing is not part of the excercise.
You don't want to capture all numbers, otherwise you would get the 5 in the id, too. I would guess, what you're looking for is numbers looking like this: $#,###.##
Here goes the expression for that:
/\$[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?/
\$ The dollar sign
[0-9]{1,3} One to three digits
(,[0-9]{3})* [Optional]: Digit triplets, preceded by a comma
(\.[0-9]+)? [Optional]: Even more digits, preceded by a period
/(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;
Let's break that into parts for explanations:
(?:\d{1,3},)* - Match any numbers separated by a thousand-divider
\d{1,3} - Match the numbers before the decimal point
(?:.\d+) - Match an arbitrary number of decimals
Flag 'g' - Make a global search to find all matches in the string
You can use it like this:
var regex = /(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;
var numbers = "$3,079.95 And Price $3,479.95".match(regex);
// numbers[0] = 3,079.95
// numbers[1] = 3,479.95
A very simple solution is the following one. Note that it will also match some invalid number strings like $..44,.777.
\$[0-9,.]+
(function () {
var reg = /\$([\d\.,]+)\s[\w\W]+\s\$([\d\.,]+)$/;
// this function used to clean inner html
function trim(str) {
var str = str.replace(/^\s\s*/, ''),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}
function getNumbersFromElement(elementId) {
var el = document.getElementById(elementId),
text = trim(el.innerHTML),
firstPrice,
secondPrice,
result;
result = reg.exec(text);
if (result[1] && result[2]) {
// inside this block we have valid prices
firstPrice = result[1];
secondPrice = result[2];
// do whatever you need
return firstPrice + ' AND ' + secondPrice;
} else {
return null; // otherwise
}
}
// usage:
getNumbersFromElement('UnitCost5');
})();
The following will return an array of all prices found in the string
function getPrices(str) {
var reg = /\$([\d,.]+)/g;
var prices =[];
var price;
while((price = reg.exec(str))!=null) {
prices.push(price);
}
return prices;
}
edit: note that the regex itself may return some false positives

Categories

Resources