I need to fix a bug in AngularJS application, which has many forms to submit data-
Every Text box in forms is accepting whitespaces(both leading and trailing) and saving them into the database. So in order to fix this I used ng-trim="true", it worked and data is getting saved correctly in the back-end.
Problem: Even after using ng-trim when I click on save/update, the form UI shows the text with white-spaces not the trimmed data. It shows correct data only when I refresh the page.
Can anyone guide me.. what will be the approach to fix this?
P.S. - I'm new to both JavaScript and Angular!
Thanks
Using trim() method works fine, but is used in newer browsers.
function removeWhitespaceUsingTrimMethod {
var str = " This is whitespace string for testing purpose ";
var wsr = str.trim();
alert(wsr);
}
Output:
This is whitespace string for testing purpose
From Docs:
(method) String.trim(): string
Removes the leading and trailing white space and line terminator
characters from a string.
Using replace() method – works in all browsers
Syntax:
testStr.replace(rgExp, replaceText);
str.replace(/^\s+|\s+$/g, '');
function removeWhitespaceUsingReplaceMethod {
var str = " This is whitespace string for testing purpose ";
var wsr = str.replace(/^\s+|\s+$/g, '');
alert( wsr);
}
Output:
This is whitespace string for testing purpose
Use string = string.trim() where string is the variable holding your string value.
When using reactive forms
this.form.controls['email'].valueChanges
.subscribe(x=>{
if(x.includes(' ')){
console.log('contains spaces')
this.form.controls['email'].setValue(x.trim())
}else{
console.log('does not contain spaces')
}
})
Related
I currently have a working WordWrap function in Javascript that uses RegEx. I pass the string I want wrapped and the length I want to begin wrapping the text, and the function returns a new string with newlines inserted at appropriate locations in the string as shown below:
wordWrap(string, width) {
let newString = string.replace(
new RegExp(`(?![^\\n]{1,${width}}$)([^\\n]{1,${width}})\\s`, 'g'), '$1\n'
);
return newString;
}
For consistency purposes I won't go into, I need to use an identical or similar RegEx in C#, but I am having trouble successfully replicating the function. I've been through a lot of iterations of this, but this is what I currently have:
private static string WordWrap(string str, int width)
{
Regex rgx = new Regex("(?![^\\n]{ 1,${" + width + "}}$)([^\\n]{1,${" + width + "}})\\s");
MatchCollection matches = rgx.Matches(str);
string newString = string.Empty;
if (matches.Count > 0)
{
foreach (Match match in matches)
{
newString += match.Value + "\n";
}
}
else
{
newString = "No matches found";
}
return newString;
}
This inevitably ends up finding no matches regardless of the string and length I pass. I've read that the RegEx used in JavaScript is different than the standard RegEx functionality in .NET. I looked into PCRE.NET but have had no luck with that either.
Am I heading in the right general direction with this? Can anyone help me convert the first code block in JavaScript to something moderately close in C#?
edit: For those looking for more clarity on what the working function does and what I am looking for the C# function to do: What I am looking to output is a string that has a newline (\n) inserted at the width passed to the function. One thing I forgot to mention (but really isn't related to my issue here) is that the working JavaScript version finds the end of the word so it doesn't cut up the word. So for example this string:
"This string is really really long so we want to use the word wrap function to keep it from running off the page.\n"
...would be converted to this with the width set to 20:
"This string is really \nreally long so we want \nto use the word wrap \nfunction to keep it \nfrom running off the \npage.\n"
Hope that clears it up a bit.
JavaScript and C# Regex engines are different. Also each language has it's own regex pattern executor, so Regex is language dependent. It's not the case, if it is working for one language so it will work for another.
C# supports named groups while JavaScript doesn't support them.
So you can find multiple difference between these two languages regex.
There are issues with the way you've translated the regex pattern from a JavaScript string to a C# string.
You have extra whitespace in the c# version, and you've also left in $ symbols and curly brackets { that are part of the string interpolation syntax in the JavaScript version (they are not part of the actual regex pattern).
You have:
"(?![^\\n]{ 1,${" + width + "}}$)([^\\n]{1,${" + width + "}})\\s"
when what I believe you want is:
"(?![^\\n]{1," + width + "}$)([^\\n]{1," + width + "})\\s"
I have the following string: "\IonSubsystem1\TRAN-88311"
I need to pull off the last word:TRAN-88311 which is an id, in a generic way.
How can I do it?
I have thought maybe found the last occurrence of '\' letter, but it is appear to me that I can't run the following order in JS :
var a = "\\IonSubsystem1\TRAN-88311";
a.lastIndexOf('\') ==> error in here.
Any other solution is welcome , thanks in advance
This is very easy.
var a = "\\IonSubsystem1\\TRAN-88311";
a = a.split("\\");
console.log(a[a.length-1]);
In your string representation, the \T is converted as a tab character.
This should do it:
var a = "\\IonSubsystem1\\TRAN-88311";var b = a.split('\\');console.log(b[b.length-1]);
Using Regex with capturing groups here is a solution.
var a = '\\IonSubsystem1\\TRAN-88311';
var id = a.replace(/(\\.*\\)(.*)/g, '$2');
alert(id);
Of course you have to escape that backslash otherwise the apex will be escaped instead (throwing the error)
Wrong
x.indexOf('\'); //The first apex opens the string, the slash will prevent the second apex to close it
Correct
x.indexOf('\\'); //The first apex open the string, the first backslash will escape the second one, and the second apex will correctly close the string
I'm currently learning Angular I'm having an issue with transforming a certain long string.
So, this is my div with a lot of lines, generated by ng-repeat:
http://pastebin.com/raw/bJqqUvpY
Yeah, it's pretty nasty, I know. What i want to do is to remove all the ng attributes and other stuff that I don't need from that string, because I'm going to pass this data to PHP via ajax.
Here's what I tried to do (angular):
$scope.updateHtml = function() {
var testVal = angular.element('#sendHtml').val();
testVal = testVal.replace(/ng-class="{'selected':selection.indexOf($index) != -1}"/g,"");
$scope.sendHtml.html = testVal;
};
But it doesn't work. Perhaps it's because of the quotation marks inside of the phrase, or is it?
This, for instance, works with a replacement of a single letter:
$scope.updateHtml = function() {
var testVal = angular.element('#sendHtml').val();
testVal = 'abcabcabc';
testVal = testVal.replace(/b/g,"");
$scope.sendHtml.html = testVal;
};
Then $scope.sendHtml.html is equal to 'acacac' like it should.
Could this be solved with another kind of RegEx?
Escape dot ., parenthesis (), and dollar $ signs.
testVal = testVal.replace(/ng-class="{'selected':selection\.indexOf\(\$index\) != -1}"/g,"");
Demo: http://regexr.com/3enmj
On the website you can examine all characters that should be escaped, by opening menu Reference - Escaped Characters.
If you need to remove all the ng-* directives as well as the html comments generated you can try the following regex.
\sng-[a-z]*="(.*?)"|(<!--(.*?)-->)
You remove a whitespace \s followed by ng- and any number of characters [a-z]* followed by double quotes and what's inside "(.*?)" as well as the html comments <!--(.*?)--> and what's inside.
Can probably be improved but it works for cleaning your input.
I am trying to clean up input and put it into a desired way. Basically, we have serialnumbers that are entered several different ways - enter delimited (newline), space, comma, etc.
My problem in my code below in testing is that new line delimited isn't working. According to w3schools and 2 other sites:
The \s metacharacter is used to find a whitespace character.
A whitespace character can be:
-A space character
-A tab character
-A carriage return character
-A new line character
-A vertical tab character
-A form feed character
This should mean that I can catch basically any new line. In Netsuite, the user is entering the value as:
SN1SN2SN3
I want this to change to "SN1,SN2,SN3,". Currently the \s RegEx is not picking up the newline? Any help would be appreciated.
**For the record - while I am using Netsuite (CRM) to get the input, the rest of this code is typical javascript and regex work. This is why I am using all 3 tags - netsuite, js, and regex
function fixSerailNumberString(s_serialNum){
var cleanString = '';
var regExSpace = new RegExp('\\s',"g");
if(regExSpace.test(s_serialNum)){
var a_splitSN = s_serialNum.split(regExSpace);
for(var i = 0; i < a_splitSN.length;i++){
if(a_splitSN[i].length!=0){
cleanString = cleanString + a_splitSN[i]+((a_splitSN[i].split(',').length>1)?'':',');
}
}
return cleanString;
}
else{
alert("No cleaning needed");
return s_serialNum;
}
}
EDITS:
1-I need to handle both if it has spaces (such as "sn1, sn2, sn3" needs to become "sn1,sn2,sn3") and this newline issue. What I have above works for the spaces.
2- I am not sure if it matters, but the field is a textarea. Does that impact this?
#Cheery found why this was happening. As I said, I got the data from Netsuite and was using the API to get the data. In the UI of Netsuite this data did look like each line was on a new line, however, when doing a console.log the values were not.
Example:
UI displayed:
sn1
sn2
sn3
Console.log displayed:
sn1sn2sn3
I was assuming the UI translated into the actual value and didn't think to check what the string was.
NetSuite multi-select fields (like the Serial Numbers transaction column) usually return all selected values as a single string, as you've noted with "sn1sn2sn3"; however, each of these values is actually separated by a non-printing character \x05. Try .split(/\x05/).join(',')
Hey all, having an issue doing string replacement for template engine code I am writing. If my tokens are 1 level deep everything works fine. Example {someProperty}. But if I try searching for a nested object it never does the replace. Example {myobj.deep.test}. I've attached the code I am playing around with. Thanks for the help!
function replaceStuff(content, fieldName, fieldValue) {
var regexstr = "{" + fieldName + "}";
console.log("regexstr: ", regexstr);
//var regex = new RegExp("{myobj\.deep\.test}", "g"); //this works as expected
var regex = new RegExp(regexstr, "g"); //this doesn't
return content.replace(regex, fieldValue);
}
replaceStuff("test: {myobj.deep.test}", "myobj.deep.test", "my value");
See this SO question about curly braces. Perhaps your browser of choice isn't as understanding as chrome is?
You need to escape the '.' characters in the string you're passing in as the fieldName parameter. Ditto for any other special regex characters that you want to be interpreted literally. Basically, fieldName is being treated as part of a regex pattern.
If you don't want fieldName to be evaluated as regex code, you might want to consider using string manipulation for this instead.
Edit: I just ran your code in FireFox and it worked perfectly. You may have something else going on here.