Issue
I have quite a similar input to output code scenario as this one: http://plnkr.co/edit/eBjenGqgo3nbnmQ7XxF1?p=preview
I am using AngularJS 1.5.7. Ng directives that my input - ( first ) textarea uses are the same as those shown in Plunkr (ng-list, ng-trim...). My output, unlike the Plunkr example, is displayed inside a ( second ) textarea, but logic is quite similar. $scope.outputValue is an output array which I am converting to string, and implementing 1 RegExp afterwards:
$scope.outputValue = $scope.outputValue.toString();
$scope.outputValue = $scope.outputValue.replace(/,/g, " | ");
Problem is that the generated string always adds an extra " | " at the end of itself. Often times an output looks like this if the user passes a couple of empty array items inside a first textarea:
var foo = "one | two | three | four | | | | |";
But what I really need to display is this:
var foo = "one | two | three | four";
The only thing that is important is to remove all the "|" that get attached to the end of the string as a replacement of ',' but the output can have "|" values as well, therefore:
var foo = "one| | ||two| | three| | four||";
would also be a valid output.
Similar thing happens with Plunkr example, as it generates empty array items and separated by commas.
Is there any RegExp that might be useful for this problem?
Solution
Instead of doing toString()
and .replace()
on the array, use .join()
.
function transform(stringArray) {
return stringArray.join(" | ");
};
//names = ["morpheus","neo","trinity"]
//output = morpheus | neo | trinity
The DEMO on PLNKR
It still outputs vertical bar characters at the end if you don't pass any value in array items.
Add a filter to remove items that are only white space:
function transform(stringArray) {
var filteredArray = stringArray.filter((s)=>(s.trim()));
return filteredArray.join(" | ");
}
The DEMO on PLNKR.
Answered By - georgeawg
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.