Can you strip out characters using a Handlebars helper? - javascript

I am using Handlebars to compile a template that returns JSON data. My issue is that I would like to create a tel link to the phone numbers which are displayed, but the format they are being returned in is: (XXX) XXX-XXXX
I know you can register a helper to take a string of numbers and then format them, but is there any way to do the reverse(strip out any non-numeric characters/spaces)?
This is the helper which does the inverse of what I am trying to do:
Handlebars.registerHelper("formatPhoneNumber", function(phoneNumber) {
phoneNumber = phoneNumber.toString();
return "(" + phoneNumber.substr(0,3) + ") " + phoneNumber.substr(3,3) + "-" + phoneNumber.substr(6,4);
});
Thanks!

Sure, you can just use a regular expression to strip out anything that's not a digit:
Handlebars.registerHelper("unformatPhoneNumber", function(phoneNumber) {
return phoneNumber.replace(/\D/g,'');
});

Nevermind, figured it out based on a non-handlebars answer.
Handlebars.registerHelper("formatPhoneNumber", function(phoneNumber) {
return phoneNumber.replace(/\D/g,'');
});

Related

replace commas with dots and add element to string

I want to replace all commas of a (number) string with dots and add another element at the same time to display the currency
so far I have this
$("#myelement").text(function () {
return $(this).text().replace(/\,/g, '.');
});
So far this works and returns for example 1,234,567 as 1.234.567 but how can I add a string/element to it so that I get 1.234.567 Dollars or 1.234.567 Rupis etc.
Just add + " Dollars" (or Rupees, etc.) to what you're returning from the function:
$("#myelement").text(function () {
return $(this).text().replace(/\,/g, '.') + " Dollars";
});
Note that as georg points out, you don't need the $(this).text() part, the callback gets the index and the old text as arguments:
$("#myelement").text(function(index, text) {
return text.replace(/\,/g, '.') + " Dollars";
});
Side note: , isn't special in regular expressions, no need to escape it (although doing so is harmless). So just /,/g, not /\,/g.

Javascript convert PascalCase to underscore_case/snake_case

How can I convert PascalCase string into underscore_case/snake_case string? I need to convert dots into underscores as well.
eg. convert
TypeOfData.AlphaBeta
into
type_of_data_alpha_beta
You could try the below steps.
Capture all the uppercase letters and also match the preceding optional dot character.
Then convert the captured uppercase letters to lowercase and then return back to replace function with an _ as preceding character. This will be achieved by using anonymous function in the replacement part.
This would replace the starting uppercase letter to _ + lowercase_letter.
Finally removing the starting underscore will give you the desired output.
var s = 'TypeOfData.AlphaBeta';
console.log(s.replace(/(?:^|\.?)([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
OR
var s = 'TypeOfData.AlphaBeta';
alert(s.replace(/\.?([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
any way to stop it for when a whole word is in uppercase. eg. MotorRPM into motor_rpm instead of motor_r_p_m? or BatteryAAA into battery_aaa instead of battery_a_a_a?
var s = 'MotorRMP';
alert(s.replace(/\.?([A-Z]+)/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
str.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
u're welcome
var s1 = 'someTextHere';
var s2 = 'SomeTextHere';
var s3 = 'TypeOfData.AlphaBeta';
var o1 = s1.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
var o2 = s2.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
var o3 = s3.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
console.log(o1);
console.log(o2);
console.log(o3);
Alternatively using lodash:
lodash.snakeCase(str);
Example:
_.snakeCase('TypeOfData.AlphaBeta');
// ➜ 'type_of_data_alpha_beta'
Lodash is a fine library to give shortcut to many everyday js tasks.There are many other similar string manipulation functions such as camelCase, kebabCase etc.
This solution solves the non-trailing acronym issue with the solutions above
I ported the code in 1175208 from Python to JavaScript.
Javascript Code
function camelToSnakeCase(text) {
return text.replace(/(.)([A-Z][a-z]+)/, '$1_$2').replace(/([a-z0-9])([A-Z])/, '$1_$2').toLowerCase()
}
Working Examples:
camelToSnakeCase('thisISDifficult') -> this_is_difficult
camelToSnakeCase('thisISNT') -> this_isnt
camelToSnakeCase('somethingEasyLikeThis') -> something_easy_like_this
"alphaBetaGama".replace(/([A-Z])/g, "_$1").toLowerCase() // alpha_beta_gamma
Problem - Need to convert a camel-case string ( such as a property name ) into underscore style to meet interface requirements or for meta-programming.
Explanation
This line uses a feature of regular expressions where it can return a matched result ( first pair of () is $1, second is $2, etc ).
Each match in the string is converted to have an underscore ahead of it with _$1 string provided. At that point the string looks like alpha_Beta_Gamma.
To correct the capitalization, the entire string is converted toLowerCase().
Since toLowerCase is a fairly expensive operation, its best not to put it in the looping handler for each match-case, and run it once on the entire string.
After toLowerCase it the resulting string is alpha_beta_gamma ( in this example )
This will get you pretty far: https://github.com/domchristie/humps
You will probably have to use regex replace to replace the "." with an underscore.
I found this but I edited it so suit your question.
const camelToSnakeCase = str => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`).replace(/^_/,'')
Good examples for js:
Snake Case
Kebab Case
Camel Case
Pascal Case
have here
function toCamelCase(s) {
// remove all characters that should not be in a variable name
// as well underscores an numbers from the beginning of the string
s = s.replace(/([^a-zA-Z0-9_\- ])|^[_0-9]+/g, "").trim().toLowerCase();
// uppercase letters preceeded by a hyphen or a space
s = s.replace(/([ -]+)([a-zA-Z0-9])/g, function(a,b,c) {
return c.toUpperCase();
});
// uppercase letters following numbers
s = s.replace(/([0-9]+)([a-zA-Z])/g, function(a,b,c) {
return b + c.toUpperCase();
});
return s;
}
Try this function, hope it helps.
"TestString".replace(/[A-Z]/g, val => "_" + val.toLowerCase()).replace(/^_/,"")
replaces all uppercase with an underscore and lowercase, then removes the leading underscore.
A Non-Regex Answer that converts PascalCase to snake_case
Note: I understand there are tons of good answers which solve this question elegantly. I was recently working on something similar to this where I chose not to use regex. So I felt to answer a non-regex solution to this.
const toSnakeCase = (str) => {
return str.slice(0,1).toLowerCase() + str.split('').slice(1).map((char) => {
if (char == char.toUpperCase()) return '_' + char.toLowerCase();
else return char;
}).join('');
}
Eg.
inputString = "ILoveJavascript" passed onto toSnakeCase()
would become "i_love_javascript"

Validating a string pattern in regex

I have the following string:
/xyz/10.2005/abc.d10.1/example
Here what I want to validate is, there should not be a space after "/xyz/".
Like It should not accept if the string is:
/xyz/ 10.2005/abc.d10.1/example
But it should accept if the string is:
10.2005/abc.d10.1/example
How can I modify the following regex to validate the above thing??
REGEX- "^\\S*((10(\\.\\d+)+)\\/([^\\/]+)(\\/\\d+[\\.+[a-zA-Z\\d]]*)?)"
Could someone help me??
This may be what you are looking for (it's a literal, you can convert it to a string if you really need to use the RegExp constructor):
var re = /^(\/\w+\/10|\s*10)\.\d+\/\w+\.\w\d+\.\d\/\w{7}/;
var s = '/xyz/10.2005/abc.d10.1/example';
var t = '/xyz/ 10.2005/abc.d10.1/example';
var u = ' 10.2005/abc.d10.1/example';
console.log(
's:' + re.test(s) + '\n' + // true
't:' + re.test(t) + '\n' + // false
'u:' + re.test(u) + '\n' // true
);
It does more than just validate the space after the /xyz/ part, I hope the rest is what you want.
actually you need to make it a lazy regex
just change it to this
^\\S*?((10(\\.\\d+)+)\\/([^\\/]+)(\\/\\d+[\\.+[a-zA-Z\\d]]*)?).*
see those ? and .* at the end
demo here : http://regex101.com/r/zJ7yX8
Here's a long RegEx:
/(?:\/[a-z]+\/)?\10\.\d{4}\/[a-z]{3}\.[a-z]\d{2}\.\d\/[a-z]{7}/i
// or the following if you don't want exact occurrences
/(?:\/[a-z]+\/)?10\.\d+\/[a-z]+\.[a-z]\d+\.\d\/[a-z]+/i
Matches:
/xyz/10.2005/abc.d10.1/example
10.2005/abc.d10.1/example
?: makes the group non-capturing.
The ? after the bracket-end symbolize it is optional.
Next is fairly simple RegEx.
For more explanation, here's a demo

Handlebars helper - returning HTML not text

I wrote a simple helper for my template. Here's the code:
Handlebars.registerHelper('splitQuote', function (string) {
if (string.indexOf('|') !== -1) {
return string.replace('|', '<span>') + '</span>';
}
return string;
});
So I pass a string, and split the string by '|' character. I also want to put second part into span tags.
Problem is, the result that is being returned is pure text, so I get span tags like a text, not HTML.
Does anyone know what's the catch?
Tnx
You don´t need to use SafeString. Instead, use the "triple moustaches" from handlebar:
From Handlebars web site, HTML Escaping section:
Handlebars HTML-escapes values returned by a {{expression}}. If you don't want Handlebars to escape a value, use the "triple-stash", {{{.
So, a simple triple quote in your html will avoid escaping:
{{{splitQuote}}}
You have to mark the string as html in your helper if you want to Handlebars not to escape it. Use Handlebars.safeString to do this. The below should suit your needs
Handlebars.registerHelper('splitQuote', function(string) {
if (string.indexOf('|') !== -1) {
return new Handlebars.SafeString(string.replace('|', '<span>') + '</span>');
}
return string;
});
As mentioned in comments you should probably escape the passed string using Handlebars.Utils.escapeExpression(string) to encode the string before you do your custom formatting. I'd recommend writing like this:
Handlebars.registerHelper('splitQuote', function(string) {
string = Handlebars.Utils.escapeExpression(string);
if (string.indexOf('|') !== -1) {
string = string.replace('|', '<span>') + '</span>';
}
return new Handlebars.SafeString(string); // mark as already escaped
});

line break introduction in confirm message string

I have a confirmation pop-up dialog in which I am passing a variable which is a comma separated string.
How can I replace the commas and introduce a line break?
I tried using replace. I tried passing '\n' separated list from back-end. But nothing seems to work — though a normal confirm() used for testing purposes is working fine.
var listcontrol = document.getElementById(id3);
var List = listcontrol.innerText;
var finallist = List.replace("\n", "\n");
if (checkboxCell.checked == false) {
if (labelCell.innerText == "Yes") {
confirm("The selected exam is present in the following certifications: " + "\n" + finallist + "\n" +
"Uplanning this exam here would unplan the same exam under other certification(s) also.");
}
}
In your code you are replacing "\n" with "\n", which would make no difference. You want to replace "," with "\n" instead, right?
var string = "Demetrius Navarro,Tony Plana,Samuel L. Jackson";
alert(string);
alert(string.replace(/,/g, "\n"));​​​​
Live test - http://jsfiddle.net/9eZS9/
Js replace is,
string.replace(searchvalue,newvalue)
var finallist = List.replace(/,/g, "\n");
If your "pop-up dialog" is a custom html/css-based dialog then newline characters would be treated (more or less) the same as space characters. You'd need to use <br> elements instead, so:
var finallist = List.replace(/,/g, "<br>");
Note the use of the regex as the first argument for replace() - this is needed in order to do a global replace.
For use in a standard confirm you'd need newline characters like you were doing, but with a regex rather than a string for the replace() search term:
var finallist = List.replace(/,/g, "\n");

Categories