Capitalize a cyrillic strings with JavaScript - angularjs

I'm making an AngularJS filter which capitalizes each word's first letter.
It works well with a-zA-Z letters, but in my case I use also cyrillic characters and I would like to make it work.
var strLatin = "this is some string";
var strCyrillic = "това е някакъв низ";
var newLatinStr = strLatin.replace(/\b[\wа-яА-Я]/g, function(l){
return l.toUpperCase();
});
var newCyrillicStr = strCyrillic.replace(/\b[\wа-яА-Я]/g, function(l){
return l.toUpperCase();
});
Here I got some CodePen example: http://codepen.io/brankoleone/pen/GNxjRM

You need a custom word boundary that you may build using groupings:
var strLatin = "this is some string";
var strCyrillic = "това е някакъв низ";
var block = "\\w\\u0400-\\u04FF";
var rx = new RegExp("([^" + block + "]|^)([" + block + "])", "g");
var newLatinStr = strLatin.replace(rx, function($0, $1, $2){
return $1+$2.toUpperCase();
});
console.log(newLatinStr);
var newCyrillicStr = strCyrillic.replace(rx, function($0, $1, $2){
return $1+$2.toUpperCase();
});
console.log(newCyrillicStr);
Details:
The block contains all ASCII letters, digits and underscore and all basic Cyrillic chars from the basic Cyrillic range (if you need more, see Cyrillic script in Unicode ranges Wiki article and update the regex accordingly), perhaps, you just want to match Russian with А-ЯЁёа-я, then use var block = "\\wА-ЯЁёа-я
The final regex matches and captures into Group 1 any char other than the one defined in the block or start of string, and then matches and captures into Group 2 any char defined in the block.

If you use Lodash, you can use _.startCase instead of your own implementation (they do it by splitting the string into words, capitalizing the 1st character of each word and then joining them back together)

Try it:
function capitalizer(string) {
return string.split(/\s/).map(function(item){
return (item.charAt(0).toUpperCase() + item.slice(1))
}).join(' ')
}
Example

Related

How to get the index of spaces of a string and relate that index of spaces to a new string in javascript?

In JavaScipt
I need to get the index of spaces of a string and relate that index of spaces to a new string.
Example:
The string: "I am okay"
The result: "Y es Iam"
Example 2:
The string: "how are you"
The result: "Iam goo d"
As you can see the index of the spaces has been preserved and related to the resulting string. I do not need anything case-sensative preserved.
I can not include code from what I've tried, as I have no idea how to go about this.
Thanks for your help!
Here's what I came up with:
var srcStrX="How are you";
var applyToStrX="I am good";
function reSpace(srcStr, applyToStr) {
var resultStr="";
var srcStrCopy=srcStr.split("");
var applyToStrSpaceless=applyToStr.split(" ").join("").split("");
while(srcStrCopy.length && applyToStrSpaceless.length) {
var character=srcStrCopy.shift();
if(character==" ") resultStr+=character;
else resultStr+=applyToStrSpaceless.shift();
};
return resultStr;
}
console.log(reSpace(srcStrX, applyToStrX));
console.log(reSpace("When you wish upon a star", "Doesn't matter who you are"));

Add Single quotes where string contains comma in AngularJS

I have a string which contains values like
var string = A,B,C
Here I want to add single quote for each comma value, expected result should be as below
output = 'A','B','C'
My angular code is
var data = {
output : this.string.split("\',"),
}
which is giving result as
["A,B,C"]
Could anyone please help on this how can I get desired output.
I am understanding your code as
var string = "A,B,C"; // because string should be in this format.
and you just need to replace "\'," from your split function to "," which will give you an array like this
var out = string.split(",");
console.log(out);
[ 'A', 'B', 'C' ] // this is the output.
as split function searches for the given expression and split the string into array.
but if you just want to modify the string without making it in array then you can use the below trick
var out = "'" + string.replace(/,/g, "','") + "'";
console.log(out);
'A','B','C' // result as u mentioned and this is of string type.

How to convert dictionary to a string angularjs

I am currently working on my project using angularjs. I got everything already it is just that, i need to convert the dictionary list to a string separated by comma. I can only do this using python.
[{"name":"john"},{"name":"mark"},{"name":"peter"}]
I want to convert them to string
"john,mark,peter"
I would really appreciate your help. :)
.map and then .join will do
var array = [{"name":"john"},{"name":"mark"},{"name":"peter"}];
var names = array.map(function(item) {
return item.name;
}).join(',');
The map() method creates a new array with the results of calling a function for every array element. Use this to loop and then add that value to a variable.
var dict=[{"name":"john"},{"name":"mark"},{"name":"peter"}];
var string;
dict.map(function(value){
//do any stuff here
string+=value["name"]+",";
});
console.log(string);
Try map function to concatenate the values:
var dict=[{"name":"john"},{"name":"mark"},{"name":"peter"}];
var str="";
dict.map(function(a){
str+=a["name"]+",";
});
//feels ironical as question has AngularJS tag
document.getElementById("log").innerText=str;
<div id="log"></div>
You can simply iterate over each key-value pair and concat the extracted value with comma.
var obj = [{"name":"john"},{"name":"mark"},{"name":"peter"}]
var result = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
result += obj[p].name + ",";
}
}
result = result.replace(/,$/g,''); // to trim trailing comma

Use dot notation with angular number filter

I have an input field. The user enters a number. I need this number to be formatted correctly with dots representing the thousands (not the decimals)
user input : 5600 -> becomes 5.600 (five thousand six hundred)
user input: 56000 -> becomes 56.000
etc
I need the number to be formatted correctly INSIDE the input field.
I have a fiddle : http://jsfiddle.net/El4a/KPeBD/1059/
This fiddle works perfectly BUT it uses the number filter from angular thus it formats the numbers with a comma-notation. I however need a dot-notation.
So I tried replacing the comma manually by a dot.
var listener = function() {
var value = $element.val().replace(/,/g, '') //delete all notations
var x = $element.val($filter('number')(value, 0)) //filter
$element.val(x).replace(/,/g, '.') //replace comma by dot
}
This didn't work.
I then tried to use a locale cdn (as can be seen in the linked fiddle).
This seemed to be the solution at first creating :
But when the next 0 is added it flips and does :
I figured I also had to change the following line
var value = $element.val().replace(/,/g, '')
to
var value = $element.val().replace(/./g, '')
but then the input field is completely unusable.
Hope someone has a solution for me!
I've removed the directive as it's not that much helpful on filtering the number.
we can use angular filter ($filter) for the same. changed the code into
myApp.filter('number', ['$filter', function ($filter) {
return function (input, symbol, fraction) {
if (input) {
var decimal = input.toString().split('.')[1],
value = input.toString().split('.')[0],
filtered = value.replace(/(?=(\d\d\d)$)/g, ".");
return (decimal) ? (fraction > 0 ? filtered + '.' + decimal.slice(0, fraction) : filtered) : filtered;
} else {
return 0
}
}
}])
sorry I've removed the entire directive section and updated the jsFiddle.
Here is the updated Demo
OMG I finally found it...
I forgot to escape the goddamn . char:
so changing
var value = $element.val().replace(/./g, '')
to
var value = $element.val().replace(/\./g, '')
made it work
48hours well spent...

Join an array of strings in Apex

Using Apex, I want to split a string and then rejoin it with the 'AND' operator as the separator.
I split the string successfully but having an issue in rejoining it.
String [] ideaSearchText = searchText.Split(' ');
// How to rejoin the array of strings with 'AND'?
How can I do this?
You can do this as of v26 (Winter 13) by passing your String[] to String.join().
String input = 'valueOne valueTwo valueThree';
String[] values = input.split(' ');
String result = String.join( values, ' AND ' );
Anonymous Apex output calling System.debug(result):
21:02:32.039 (39470000)|EXECUTION_STARTED
21:02:32.039 (39485000)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
21:02:32.040 (40123000)|SYSTEM_CONSTRUCTOR_ENTRY|[3]|<init>()
21:02:32.040 (40157000)|SYSTEM_CONSTRUCTOR_EXIT|[3]|<init>()
21:02:32.040 (40580000)|USER_DEBUG|[5]|DEBUG|valueOne AND valueTwo AND valueThree
Note if the string object is too large you will get the exception Regex too complicated. In this case you can do something like the following:
Blob blobValue = (Blob)record.get(blobField);
// Truncate string then split on newline, limiting to 11 entries
List<String> preview = blobValue.toString().substring(0,1000).split('\n', 11);
// Remove the last entry, because The list’s last entry contains all
// input beyond the last matched delimiter.
preview.remove(preview.size()-1);
// In my use-case, I needed to return a string, and String.join() works
// as the reverse of split()
return String.join(preview, '\n');

Resources