Identifying end and start of input and saving them as variables - javascript

I'm looking for something in JS that could help me identify when a set of numbers begins and ends(by a space or other character that is not a number or letter).
For example: let's say the user inputs - 2424+345 (yes I'm building a calculator). I want to identify when the number starts and ends (ends when the + sign starts). Then it saves it as a variable for later use and continues reading the second set of numbers and assigns it to a variable as well. I can loop through the input, but what I don't know is how to write the rule that does all the checking and assigning.
Regex seems to be the way to go, but I have very little experience with it (have done some simple form validation with it).

To find the first number in a string, the regular expression would be /^\d+/, so for instance:
var str = "2424+345";
var match = /^\d+/.exec(str);
if (match) {
// match[0] now contains "2424"
}
Put that in a loop, consuming the operators...

Related

javascript word in sentence matching

I'm currently trying to find matching words within sentences, and I have a method that mostly works. It's working on a HTMLNode.textContent where I currently use the indexOf method to find a match.
let exists = node.textContent.indexOf(x.searchText) > -1
I need it to match exactly, including any spaces and special characters in the word, which works with indexOf, but I also want to be able to create exceptions to this exact search.
For example the word "Burnett’s" should be equal to "Burnett's" despite the apostrophe formats being different.
There are quite a lot of checks when this runs, so preferably I want something fast without having to check every word if it contains either of those apostrophes and if so remove it so it's not part of the comparison. Are there any better ways to check for or do it on?
You could replace every exception variant to a single one to check against:
function cleanText(str) {
return str.replace(/[`’]/g,"'");
}
let exists = cleanText(node.textContent).indexOf(cleanText(x.searchText)) > -1;
You can easily chain additional exceptions in the cleanText function, for example:
function cleanText(str) {
return str.replace(/[`’]/g,"'").replace(/#/g, " at ").replace(/&/g, " and ");
}

using regular expression to hide email address from spam bots

i am dynamically rendering multiple email addresses (mail to: ) on a webpage.
i obliviously need to hide these from spam bots.
the simplest solution that i found is this:
link
this involves putting a fake characters: "X" within the email address and then removing these once the link is click, copied or pasted.
it works- however the drawback is that it remove all "x"'s from the address. since i cannot guarantee that my dynamically rendered emails will not contain "x" this solution-as is, it not right for me.
a better solution would be to put 3 or more 'X' at the start/end of each email address and then using the above code to remove them once the link is clicked
i.e:
<a href="mailto:XXXcontact#domain.comXXX"
onmouseover="this.href=this.href.replace(/x/g,'');">link</a>
what i now need to do is use regular expression to THEN remove the first 3 'x' from the email address when its clicked
i tried the below but it did not work:
<a href="mailto:xxxcontact#domain.comXXX"
onmouseover="this.href=this.href.replace(^[\s\S]{0,3});">link</a>
The replace method expects two parameters - first the regex you're matching against, and second the value you want to replace matches with. It is also expected that your regex pattern will have flags to explain the behaviour of matches. For instance, g will match over the string it is operating on, globally, and i will match in a case-insensitive manner.
The regex you're after here would probably be more along the lines of:
^(mailto\:)x{3}(.*)x{3}$
That is, you're aiming to capture mailto:, which is expected at the beginning of the string, then to discard 3 x or X chars, followed by capturing the email address, but not the 3 x or X chars that are expected at the end of the string.
This would fit into the replace method in the following manner:
.replace(/^(mailto\:)x{3}(.*)x{3}$/i, '$1$2')
That said, would it not be fair to say that an email address could be inclined to include x or X characters consecutively? If so, you should either replace each occurrence of x{3} and the corresponding matches that you're prepending/appending to the email address with something less likely to be contained in an email address, or devise an alternative approach to the problem.
You could try something along the lines of
link
It would basically replace the occurences of ^$^ instead of something common as X or XXX
I would avoid adding more or less common characters in your mail address for obfuscation purposes. Rather try some kind of very basic encryption, such as toggling the bits or taking the string char by char, and increasing the char code by a fixed value.
Example:
var mailto = "mailto:contact#domain.com";
var obfuscated = "";
for (let i = 0; i < mailto.length; i++) {
obfuscated += String.fromCharCode(mailto.charCodeAt(i) + 7);
}
//obfuscated now looks like this: "thps{vAjvu{hj{Gkvthpu5jvt"
//to reverse the process, do the same thing and subtract 7.
//You could extract the code to a method that you simply call with "onmouseover"
Hope this helps, despite not precisely answering your question :)

validate a textbox that Doesn't Start or End With Special Character

I have some requirements that I need to implement a text box that doesn't allow special character at starting and ending of the string but it has option to allow in middle of the word
example:
1)Some_#thing --True
2)_#2someThing --False
3)something_# --false*
$(function () {
$('#text').on("change", function (e) {
if (this.value.match(/^[a-z0-9](?!.*?[^\na-z0-9]{100}).*?[a-z0-9]$/)) {
this.value = this.value.replace(/^[a-z0-9](?!.*?[^\na-z0-9]{100}).*?[a-z0-9]$/, '');
$("#eror").text("Accepts only Alphabets");
}
});
Try pattern something like this ^[a-z0-9](?!.*?[^\na-z0-9]{100}).*?[a-z0-9]$
Here is the Demo of it. you can check it. There's some error in your code too, here i had created one new fiddle. according to that you can modify your code. and it may work.
1> change your function to .change as i used in fiddle
2> compare pattern to string such like pattern.test(string).
New Fiddle with Working Pattern. hope so above solution work for you.
It looks like you may be looking for the reverse of what yash posted, screening for instances that break the rule, rather than conform to it.
Your 'if' conditional appears to be looking for a result that returns true if the special-character rule has been broken, so you would probably want something along the lines of:
//allows only letters and numbers at the start and end
/^[\W_\s].*$|^.*[\W_\s]$/
//allows only letters (and not numbers) at the start and end
/^[^A-Za-z_\s].*$|^.*[^A-Za-z_\s]$/
Both will allow special characters within the string itself, outside of the starting and ending characters, without triggering your boolean, but will trigger it if the strings starts or ends with those same characters.
As a side note, if you are only interested in testing for a regex match, and not with actually returning the regex matches, you should use:
regex.test('string')
//instead of
string.match(/regex/)
match is overkill for your needs here and will only slow down your application. test returns its result directly in boolean form and does so much quicker than match.
MDN Section on using 'test'
(if you are interested in learning more about this specific use case)

Allow only digit, comma or dot in the user input in JS

I have a user input where only a certain set of characters is allowed. That is, user should be able to enter only a number, possibly with floating point. User may use either comma or dot as a separator.
I've decided to implement this using JS replace function. My approach is to replace everything that doesn't match the set with empty string.
I've sorted out the regex to match the set pretty quickly, here it is:
^\d+[,.]{0,1}\d+$
I know it's probably not ideal, but it's quite okay since there is a server-side validation anyway.
However, no matter how hard I tried, I was not able to figure out how to replace anything that doesn't match this regex with empty string.
Here's how I use replace:
var cleanInputOut = function (element) {
element.value = element.value.replace(/<RegEx goes here>/g, '')
}
I am probably doing it wrong. I would be okay even with quite simple functionality - simply replace any non-digit, not comma and not dot with empty string. I've tried negative lookahead in regex but unfortunately I was not able to make it work as I want to.
It looks like I figured it out using
/[^\d,.]/g
So the function is
var cleanInputOut = function (element) {
element.value = element.value.replace(/[^\d,.]/g, '')
}
I don't really get why the ^ character is used both to mark a negated set and the beginning of the line, but it appears to be working.
I tried this regex before and it behaved quite strangely from time to time but I am not sure the issue was with the regex itself. Anyway, any advices as to the approach or regex are welcome.

Bookmarklet - Verify URL format and extract substring

I'm trying to build a bookmarklet that preforms a service client side, but I'm not really fluent in Javascript. In my code below I want to take the current page url and first verify that it's a url following a specific format after the domain, which is...
/photos/[any alphanumeric string]/[any numeric string]
after that 3rd "/" should always be the numeric string that I need to extract into a var. Also, I can't just start from the end and work backwards because there will be times that there is another "/" after the numeric string followed by other things I don't need.
Is indexOf() the right function to verify if the url is the specific format and how would I write that expression? I've tried several things related to indexOf() and Regex(), but had no success. I seem to always end up with an unexpected character or it just doesn't work.
And of course the second part of my question is once I know the url is the right format, how do I extract the numeric string into a variable?
Thank you for any help!
javascript:(function(){
// Retrieve the url of the current page
var photoUrl = window.location.pathname;
if(photoUrl.indexOf(/photos/[any alphanumeric string]/[any numeric string]) == true) {
// Extract the numeric substring into a var and do something with it
} else {
// Do something else
}
})();
var id = window.location.pathname.match(/\/photos\/(\w+)\/(\d+)/i);
if (id) alert(id[1]); // use 1 or 2 depending on what you want
else alert('url did not fit expected format');
(EDIT: changed first \d* to \w+ and second \d* to \d+ and dig to id.)
To test strings for patterns and get their parts, you can use regular expressions. Exression for your criteria would be like this:
/^\/photos\/\w+\/(\d+)\/?$/
It will match any string starting with /photos/, followed by any alphanumeric character (and underscore), followed by any number and optional / at the end of string, wrapped in a capture group.
So, if we do this:
"/photos/abc123/123".match(/^\/photos\/\w+\/(\d+)\/?$/)
the result will be ["/photos/abc123/123", "123"]. As you might have noticed, capture group is the second array element.
Ready to use function:
var extractNumeric = function (string) {
var exp = /^\/photos\/\w+\/(\d+)\/?$/,
out = string.match(exp);
return out ? out[1] : false;
};
You can find more detailed example here.
So, the answers:
Is indexOf() the right function to verify if the url is the specific
format and how would I write that expression? I've tried several
things related to indexOf() and Regex(), but had no success. I seem to
always end up with an unexpected character or it just doesn't work.
indexOf isn't the best choice for the job, you were right about using regular expression, but lacked experience to do so.
And of course the second part of my question is once I know the url is
the right format, how do I extract the numeric string into a variable?
Regular expression together with match function will allow to test string for desired format and get it's portions at the same time.

Categories

Resources