Add Single quotes where string contains comma in AngularJS - 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.

Related

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

Capitalize a cyrillic strings with JavaScript

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

Convert array in quotation marks to just an array

I currently have a string, that's supposed to be an Array:
var content = "['A','B','C']"
//What I want -> var content = ['A', 'B', 'C']
I need to remove the quotation marks, so that it's just an Array, i.e. String to Array. How would one attempt that?
This looks similar to JSON syntax except that the single quotes should be double quotes.
Well then, let's just do that:
let source = "['A','B','C']"
Replace single quotes with double quotes:
let content = source.stringByReplacingOccurrencesOfString("'", withString: "\"")
Then convert the String to NSData (becomes valid JSON):
guard let data = content.dataUsingEncoding(NSUTF8StringEncoding) else { fatalError() }
Finally, convert the JSON data back to a Swift array of Strings:
guard let arrayOfStrings = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String] else { fatalError() }
Result:
print(arrayOfStrings)
["A", "B", "C"]
print(arrayOfStrings[1])
"B"
Here's a semi-hacky solution to your specific example.
let content = "['A','B','C']"
var characters = content.characters
characters.removeFirst(2) // Remove ['
characters.removeLast(2) // Remove ']
let contentArray = String(characters).componentsSeparatedByString("','")
print(contentArray) // ["A", "B", "C"]
Disclaimer/Warning:
This solution isn't robust as it expects your array to only contain objects wrapped in ' characters. It will however work for any length of string (e.g. replacing A with foo will work).
If your actual content string is any more complex than what you have here then I would take Rob's advice and try JSON serialization (especially if this string comes from a place you don't control like the server).
You could do this one:
let arr = content.componentsSeparatedByCharactersInSet(NSCharacterSet (charactersInString: "['],")).filter({!$0.isEmpty})
Explanation:
First, we split the string into an array based upon separators like: [, ', ,, ]
We now have an array with some empty strings, we use filter() to remove them.
And Voila !
Warning:
like #nebs' warning, carefull with this solution. If your string is composed by more complexe strings (ex: "['Hello [buddy]', 'What's up?', 'This is a long text, or not?']"), especially string composed with the separators, you will get an array that will not match with your expected result.

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

VBA. Array for search or replace

Need to found any symbol of array.
For example:
replace(string,[a,b,c,e,f,g],"a1b2c3d4e567");
result = "1234567"
How do it ?
If your goal is to remove all non-numeric characters, the following will work:
' Added reference for Microsoft VBScript Regular Expressions 5.5
Const s As String = "a1b2c3d4e567"
Dim regex2 As New RegExp
Dim a As String
regex2.Global = True
regex2.Pattern = "[^0-9]"
Dim a As String = regex2.Replace(s, "")
MsgBox (a) ' Outputs 1234567
If you are looking for specific characters, change the pattern.
AFAIK you are going to have to do this by consecutive calls to replace
result = "a1b2c3d4e567"
result = replace(result,"a","")
result = replace(result,"b","")
result = replace(result,"c","")
etc

Resources