Remove empty characters, blank characters, invisible characters in jQuery [duplicate] - javascript

This question already has answers here:
Remove not alphanumeric characters from string
(10 answers)
Regular expression to remove anything but alphabets and '[single quote]
(1 answer)
javascript regex to return letters only
(6 answers)
Ignoring invisible characters in RegEx
(2 answers)
Closed 2 years ago.
I am performing a validation in html text box which should pass only alphabets(a-z/A-Z) and few special characters like (*,& etc..). Otherwise it should show error some error.
I had written a JavaScript function which does the same.
function removeInvalidCharacters(selectedElement) {
if (selectedElement && typeof selectedElement.val() !== typeof undefined && selectedElement.val() != "") {
selectedElement.val(selectedElement.val().replace(/[\u0000-\u001F]|[\u007F-\u00A0]/g, "").replace(/\\f/g, "").replace(/%/g,""));
}
}
I am filtering selectedElement before passing to the function removeInvalidCharacters.
$("#name").val(toASCII($("#name").val()));
var selectedElement = $("#name").val();
But now I am facing a scenario in which empty characters, blank characters, invisible characters and whitespace characters are bypassing my regex. I could see some invisible characters are present in my name field. I want to replace these characters.
In further investigation I could found that Invisible characters - ASCII
characters mentioned in this link are the culprits. I need to have a regex to catch them and replace them.
Eg: AAAAAAAAAAAA‎AAAAAAAAAAA is the value in text field. Now if we check $("#name").val().length, it gives 24 ,even though we could see only 23 characters. I need to remove that hidden character.
Please help me with this scenario. Hope my query is clear
UPDATE:
var result = selectedElement.replace(/[\u200B-\u200D\uFEFF]/g, ''); fixed my problem.
Thank you all for the support.

If you want to allow only (a-z/A-Z) like you mention, try this:
str = str.replace(/[^a-zA-Z]/g, '');

Include the chars you want to keep instead of the ones you do not want, since that list may be incomplete
Otherwise look here: Remove zero-width space characters from a JavaScript string
const val = `AAAAAAAAAAAA‎AAAA**AAAAAAA`;
const cleaned = val.replace(/[^A-Za-z*]/g,"");
console.log(val.length,cleaned.length);

Related

Getting a true or false reply to a Regex match? [duplicate]

This question already has answers here:
Return true/false for a matched/not matched regex
(5 answers)
Closed 3 years ago.
I'm trying to match an entire string against a regex formula. This is for validating if a phone number field is likely correct (just based on allowed characters, anyone can make up an number). I've played with Regex before but never truly understood the nuances that make it powerful.
Below I have my dummy phone number and I have the regex I'm using. As you can see I'm simply comparing the length of the match vs the length of the string and if they match the number must be valid.
Is there a way to get a simple true/false reply from a Regex check on an entire string?
var num = '+1 (888) 456-7896';
var regex = /[0-9+ ()-]*$/;
var found = num.match(regex);
console.log(found[0].length);
console.log(num.length);
You can use test()
var found = regex.test(num);

Javascript - Make specific text a link [duplicate]

This question already has answers here:
Detect URLs in text with JavaScript
(15 answers)
Closed 4 years ago.
I'm looking at a 'to do' list application that uses JavaScript.
One of the functions converts text in to a hyperlink when https, https or ftp is present.
I'd like to expand this so if my text contains # followed by any 5 digit number, that becomes a link as well. The URL should be http://192.168.0.1/localsite/testschool/search.php?id=ID
where ID is the # and 5 digit number.
This is the current Javascript:
function prepareHtml(s)
{
// make URLs clickable
s = s.replace(/(^|\s|>)(www\.([\w\#$%&~\/.\-\+;:=,\?\[\]#]+?))(,|\.|:|)?(?=\s|"|<|>|\"|<|>|$)/gi, '$1$2$4');
return s.replace(/(^|\s|>)((?:http|https|ftp):\/\/([\w\#$%&~\/.\-\+;:=,\?\[\]#]+?))(,|\.|:|)?(?=\s|"|<|>|\"|<|>|$)/ig, '$1$2$4');
};
called using prepareHtml(item.title)
Any idea how I can do this ?
I've worked out regex to match the # and 5 digits is ^#([0-9]{5}) but I'm not sure how to implement this in the function.
Thanks
Looks to me that the pattern & replace string can be simplified a bit.
function urls2links(s)
{
return s.replace(/(^|[\s>])(www\.)/gi, '$1http://$2')
.replace(/\b(((https?|ftps?):\/{2})(\S+?))(?="|<|>|[\s<>\"]|$)/ig, '$1');
};
var str = 'blah http://192.168.0.1/localsite/testschool/search.php?id=#12345 \nblah www.foo.com/bar/" blah';
console.log('--\n-- BEFORE\n--');
console.log(str);
console.log('--\n-- AFTER\n--');
console.log(urls2links(str));
Although I'm not too sure about needing to include the character entities |"|<|> in the lookahead.
But I'm guessing you also deal with encoded strings.

Firefox Javascript: Remove non-numeric characters from input of type "number" - FF issue [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 6 years ago.
the task looks simple. I have to remove non-numeric characters from an input field of type "number" on keyup in firefox.
The code:
$("#field").on("keyup", function() {
regex = /[\\D]+/;
$(this).val( $(this).val().replace(regex, '') );
});
Unfortunately as soon as a non-numeric character enters the field, its whole content gets replaced by the empty string.
For example:
234d = emptied > should be 234
Solution (here because the question has been closed):
This example works. I found out that it has to do with the field type. If the input in the field of type "number" contains non numeric characters, firefox shows the input but doesn't store it in the input object. As soon as I use a text input everything works fine. Seems to be a Firefox issue.
I think this question is NOT duplicate because it seems to regard a Firefox issue with input fields of type "number".
var val = '234d'.replace(/[^0-9]/g, '');
console.log(val);
var myString = '234d';
Try this line:
myString = myString.replace(/\D/g,'');
Reference:
strip non-numeric characters from string

How do I properly use RegExp in JavaScript and PHP? [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 6 years ago.
How do I properly use RegExp?
var text = "here come dat boi o shit waddup";
var exmaple = /[a-zA-Z0-9 ]/; // allowes a-zA-Z0-9 and whitespaces but nothing else right?
example.test(test); // would return true right?
text = "%coconut$§=";
example.test(text); // would return false right?
//I know this is very basic - I started learnig all this about week ago
Are JS RegExp's the same as PHP RegExp's?
How do I define banned characters instead of defining allowed characters?
How do I make it so that the var text has to contain 3 (or more) numbers/letters?
How do I include / or ",'$ etc. in my pattern?
No.
Use ^ character (i.e. [^abc] will exclude a, b and c)
Use [A-Za-z]{3} for letters and \d{3} for digits. If you want 3 or more, use \d{3,}
Use escape character (\/, \', \", '\$')

Tricky RegEx Capture [duplicate]

This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Closed 6 years ago.
I've got a couple strings and I need to pull characters out that appear between double quotes. The problem is, I want to grab them in groups.
var str = 'FF\"J"A4"L"';
var results = str.match(/\"(.*)\"/);
This returns everything between the first and last double quote. In this case it returns J"A4"L but what I need it to return is J and L.
The content between quotes is pretty much any unicode character like letters and numbers including as }, =, and #.
Any ideas on how to complete this with regex?
It sounds like the content between quotes is any character except for a quote, in which case you can get away with
/"([^"]*)"/
what you're looking for is this with the /g "global flag":
/("[^"]*")/g
In your example, it's like this:
var str = 'FF\"J"A4"L"';
var results = str.match(/("[^"]*")/g);
When doing this, results would be [""J"", ""L""], which contains the entire match (which is why the extra quotes are there).
If you wanted just the matched groups (which returns just the groups, not the whole match area), you would use exec:
var str = 'FF\"J"A4"L"';
var results = []
var r = /("[^"]*")/g
match = r.exec(str);
while (match != null) {
results.push(match[1])
match = r.exec(str);
}
Now, results is ["J", "L"]

Categories

Resources