how to make first letter capital in of string in angular js - regex

I am trying to make a filter which show first letter capital of string .I am able to solve the problem but when I have one Question on that .I need to understand the regex .Mean what regax is doing here .
http://codepen.io/anon/pen/JddwwV
Could you please tell me what is the meaning of regex replace(/([^\W_]+[^\s-]*)
what is use of this expression.
angular.module('CustomFilter', []).
filter('capitalize', function() {
return function(input, all) {
console.log(input)
return (!!input) ? input.replace(/([^\W_]+[^\s-]*) */g, function(txt){
console.log(txt+":txt")
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}) : '';
}
});
function Ctrl($scope) {
$scope.msg = 'hello, world.';
}

Related

phrase search in meteor search-source package

I have a meteor app for which I added the search-source package to search certain collections and it works partially. That is, when I search for the term foo bar it returns results for each of "foo" and "bar". This is fine, but I want to also be able to wrap the terms in quotes this way: "foo bar" and get results for an exact match only. at the moment when i do this i get an empty set. Here is my server code:
//Server.js
SearchSource.defineSource('FruitBasket', function(searchText, options) {
// options = options || {}; // to be sure that options is at least an empty object
if(searchText) {
var regExp = buildRegExp(searchText);
var selector = {$or: [
{'fruit.name': regExp},
{'fruit.season': regExp},
{'fruit.treeType': regExp}
]};
return Basket.find(selector, options).fetch();
} else {
return Basket.find({}, options).fetch();
}
});
function buildRegExp(searchText) {
// this is a dumb implementation
var parts = searchText.trim().split(/[ \-\:]+/);
return new RegExp("(" + parts.join('|') + ")", "ig");
}
and my client code:
//Client.js
Template.dispResults.helpers({
getPackages_fruit: function() {
return PackageSearch_fruit.getData({
transform: function(matchText, regExp) {
return matchText.replace(regExp, "<b>$&</b>")
},
sort: {isoScore: -1}
});
}
});
Thanks in advance!
I've modified the .split pattern so that it ignores everything between double quotes.
/[ \-\:]+(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/
Thus, you can simply wrap an exact phrase search in double quotes and it won't get split.
There is one more thing; since we don't need the quotes, they are removed in the next line using a .map function with a regex that replaces double quotes at the start or the end of a string part: /^"|"$/
Sample code:
function buildRegExp(searchText) {
// exact phrase search in double quotes won't get split
var arr = searchText.trim().split(/[ \-\:]+(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/);
var parts = arr.map(function(x){return x.replace(/^"|"$/g, '');});
return new RegExp("(" + parts.join('|') + ")", "ig");
}
console.log(buildRegExp("foo bar"));
console.log(buildRegExp("\"foo bar\""));

Regex to match sub string of a string

I need to construct a regular expression to match a given value to the brand field of my product array. For instance, given the parameter "am", an array of the following products would be returned: [Amana, Mama, etc]. How do I complete this function?
public searchProduct(term) {
this.products.forEach(product => {
if (product.brand.match(`${term}`)) {
console.log('mtch found', product.brand)
}
});
return of(this.products)
}
Unless you have some special reasons to use regex, you can use filter and includes to return only items of your array containing your substring
public searchProduct(term) {
return this.products.filter(x => x.brand.includes(term))
}

What is the equalient of JavaScript's "s.replace(/[^\w]+/g, '-')" in Dart language?

I am trying to get the following working code in JavaScript also working in Dart.
https://jsfiddle.net/8xyxy8jp/1/
var s = "We live, on the # planet earth";
var results = s.replace(/[^\w]+/g, '-');
document.getElementById("output").innerHTML = results;
Which gives the output
We-live-on-the-planet-earth
I have tried this Dart code
void main() {
print( "We live, on the # planet earth".replaceAll("[^\w]+","-"));
}
But the output becomes the same.
What am I missing here?
If you want replaceAll() to process the argument as regular expression you need to pass a RegExp instance. I usually use r as prefix for the regex string to make it a raw string where not interpolation ($, \, ...) takes place.
main() {
var s = "We live, on the # planet earth";
var result = s.replaceAll(new RegExp(r'[^\w]+'), '-');
print(result);
}
Try it in DartPad

Groovy string replace

I'm working on some Groovy code to take text that's meant to be a Tweet, and turn all hashtags into web-links to the Twitter hashtag. In fact, I have that code working, but it fails when there's a bare # in the text that's meant to be read as a "number sign" instead of a hashtag.
The working (except for that edge case) code is:
static replaceHashTags(input) {
while (input.contains(/#/)) {
input = input.replaceAll(/(.*)#(\w+)(.*)/, { all, before, hashtag, after ->
"${before}<a href='https://twitter.com/hashtag/${hashtag}'>${hashtag}</a>${after}"
})
}
input.replaceAll(/<a href='https:\/\/twitter.com\/hashtag/, '#<a href=\'https://twitter.com/hashtag')
}
Instead of breaking what is mostly-working code before I had a solution, I wrote a test class to try out my new matching code. It's failing, and I can't figure out why. Here's the test class:
class StringTest {
def checkContains(string, expression) {
string.contains(expression)
}
#Test
void shouldTestSomethingElse() {
assert (checkContains('This is a string', /is/)) // Passes
assert !(checkContains('This is a string', /werigjweior/)) // Passes
assert (checkContains('#This tweet starts with a hashtag', /#This/)) // Passes
assert (checkContains('#This tweet starts with a hashtag', /#(\w+)/)) // Fails.
}
}
As I said, I'm not sure why that last assert fails. What my expectation was going into this exercise was that I could simply replace while (input.contains(/#/)) { with while (input.contains(/#(\w+)/)) {...But that doesn't seem to be the case.
I'm not convinced string.contains() accepts regex as argument. This works for me:
def checkContains(string, expression) {
string =~ expression
}
assert (checkContains('This is a string', /is/))
assert !(checkContains('This is a string', /werigjweior/))
assert (checkContains('#This tweet starts with a hashtag', /#This/))
assert (checkContains('#This tweet starts with a hashtag', /#(\w+)/))
Use ==~ to match the whole string.

Added plus sign before number input in angularjs

I am using this directive to keep user typing only number into input tag.
app.directive('validNumber', function () {
return {
require: '?ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
if (!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function (val) {
if (angular.isUndefined(val)) {
var val = '';
}
var clean = val.replace(/[^0-9\.]/g, '');
var decimalCheck = clean.split('.');
if (!angular.isUndefined(decimalCheck[0])) {
decimalCheck[0] = decimalCheck[0].slice(0, 10);
if (!angular.isUndefined(decimalCheck[1])) {
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
else {
clean = decimalCheck[0];
}
//console.log(decimalCheck[0][0]);
}
if (!angular.isUndefined(decimalCheck[1])) {
decimalCheck[1] = decimalCheck[1].slice(0, 3);
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function (event) {
if (event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
But now i want to custome this, that means user can type ONLY ONE of "+" or "-" in the first. I think i have to change this pattern of
var clean = val.replace(/[^0-9\.]/g, '');
i also try to change into val.replace(/[^0-9.+-]/g, ''). It works but incorrectly, with this pattern user can type more "+" and "-" in any position of input field. I just wanna keep user typing ONLY ONE of "+" or "-" in the first like "+1234" or "-1234"
This is more of a regex problem than an AngularJS one, so you might have more luck there: https://stackoverflow.com/questions/tagged/regex
I'll try help you though. I think the regex you want matches a single +-, then any number of digits, then optionally a decimal point, then any number of digits. A single regex to match that is:
^[+-]?[0-9]*\.?[0-9]*
Have a read about groups and the '?' operator. This regex allows:
+.
-.
which don't make sense as input. You could design clever regexes to omit those results, but I think it would be easier to check the entry programmatically.
Finally, there are also very likely regexes online to help you solve any regex problem you ever come across more comprehensivley than you could. Just google an english description next time, and check out this for what you want:
http://www.regular-expressions.info/floatingpoint.html