Display all special characters found in a value - javascript

I have an input element and on click of a button I check if its value contains a set of special characters and return a Boolean and it works fine. What I am trying to achieve is once the Boolean is returned if any special character is found in the value I want to display those special characters in a p tag. How can I achieve this? Thanks in advance.
const format = /[ `!##$%^&*_+-=\[\]{};':"\\|<>\/?~]/
const value = $('input').val()
$('button').on('click', function() {
if (format.test(value) == true) {
//something like this
$('p').html(the found special character + 'not allowed')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<button>click me</button>
<p></p>

If you are looking to find non alphanumeric characters, I would use /[^A-Z0-9,]/ig instead. Also using match allows you to see if results exist and displaying them
const format = /[^A-Z0-9,]/ig
$('button').on('click', function() {
$('p').html("")
const value = $('input').val()
const results = value.match(format)
if (results) {
$('p').html(results.join(',') + ' is not allowed')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<button>click me</button>
<p></p>

You can use String.prototype.match function instead of Regexp.prototype.test.
Match function will give you information about result and if you want to see all results you have to use g flag.
It will return array which contains all matches and it will return null if there is not any match.
const format = /[ `!##$%^&*_+-=\[\]{};':"\\|<>\/?~]/g
$('button').on('click', function() {
const value = $('input').val()
const result = value.match(format)
if (result) {
$('p').html(result.join(',') + ' is not allowed')
}
})
More information about match - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
Also you have to put code of getting value of input inside onclick event, because you want to get value of input when you clicked on button not when script executed.

Related

Caps and Lowercase input that also generates in output

I've been trying to put together an input where the text automatically capitalizes the first letter of each word and makes all other letters lowercase for that word. I had some success using that for just making everything lower case after the first letter for the input with this:
<input type = "text" size="8" name="textfield1" id="textfield1" />
with the javascript being
document.getElementById('textfield1').addEventListener("keyup", () => {
var inputValue = document.getElementById('textfield1')['value'];
if (inputValue[0] === ' ') {
inputValue = '';
} else if (inputValue) {
inputValue = inputValue[0].toUpperCase() + inputValue.slice(1).toLowerCase();
}
document.getElementById('textfield1')['value'] = inputValue;
});
I tried adding map(), split(), and join() in various ways based off of lessons I've found (I'm learning on my own, no formal training since high school) for use in a string with the console.log methods but I'm confused on how I can apply this to an input. It would take too long to note everything I've tried but one thing I did was this:
document.getElementById('textfield1').addEventListener("keyup", () => {
var inputValue = document.getElementById('textfield1')['value'];
if (inputValue[0] === ' ') {
inputValue = '';
} else if (inputValue) {
input.content = input.content.split(' ').map(function(inputValue) {
return inputValue[0].toUpperCase() + inputValue.slice(1).toLowerCase();
}).join(' ');
}
document.getElementById('textfield1')['value'] = inputValue;
});
I'm not sure what I'm missing here. I'm sure there's something that I'm not seeing or understanding. I also tried looking to see if there was something similar listed on here or elsewhere in relation to this and inputs but I didn't see anything specific to what I was looking for.
I want the input to remain the same for what comes up with the output into another box when it gets copied over.
Example of what I'm trying to do is:
input of textfield: heLlo OuT thERe!
output to another textarea with the click of a button: Hello Out There!
Your second version would be correct. However in this code:
else if (inputValue) {
input.content = input.content.split(' ').map(function(inputValue) {
return inputValue[0].toUpperCase() + inputValue.slice(1).toLowerCase();
}).join(' ');
}
You started to use some input.content instead of the inputValue variable. Most probably yout mistake lies there.
You can use this regex replace to change a sentence to Proper Case:
const regex = /\b(\w)(\w*)/g;
const input = 'Fix this lower and UPPER to Proper'
let result = input.replace(regex, function(m, c1, c2) {
return c1.toUpperCase() + c2.toLowerCase()
});
console.log('result: ', result);
// => 'Fix This Lower And Upper To Proper'
Explanation of regex:
\b -- word boundary
(\w) -- capture group 1: a singe word character
(\w*) --capture group 2: zero to multiple word characters
g -- flag for global, e.g. run pattern multiple times
replace function: parameter c1 contains capture group 1, c2 contains capture group 2

how to prevent adding scripts in input fields

I need to prevent adding scripts inside input fields.is there any way to prevent adding javascript codes in text fields/text areas?
function filter($event) {
var regex = /[^a-zA-Z0-9_]/;
let match = regex.exec($event.target.value);
console.log(match);
if (match) {
$event.preventDefault();
} else {
return true;
}
}
You can sanitize the input by defining the blacklist regex which contains the patterns not allowed by the input and then replaced the part of input string with empty string if matched with the blacklist regex.
For now I just added a simple blackList regex (You can modify it as per your requirement) which will replace all the text comes between < and >. For Ex: If user enter <script>Hello</script> (This whole input text will get replaced with the empty string on keyup event.
const blackList = /<+>/ig
function sanitizeInput() {
const inputStr = document.getElementById('inputStr').value;
console.log('inputStr', inputStr)
document.getElementById('result').innerHTML = inputStr?.replace(blackList, '')
}
<input type="text" id="inputStr" onkeyup="sanitizeInput()"/>
<div id="result"></div>

Validate input of any two specific letters say 'a' and 'i' in JavaScript and replace 'a' with # and 'i' with?

I'm a newbie and need help here.
We need a input string from an user.
The input string must contain both letters 'a' and 'i'. If it doesn't contain both then we reject the input and alert the user.
If the input string contains both 'a' and 'i' then we replace a with # and i with !.We then print the output.
For example: aletis-->#lert!s
I tried
var check = /[aiAI]/;
but this takes input even if only either a or i is satisfied.
If you're really new with regex, I would advise you to do it in two steps,as this would be far more clear to read.
"alertis".replace(/a/gi, "#").replace(/i/gi, "!");
/a/gi means find "a" with the /gi meaning "case insensitive" and global.
if (/(?=.*a)(?=.*i).*/.test('aletis')) {
const result = "aletis".replace(/a/gi, "#").replace(/i/gi, "!");
// Rest of your code
} else {
// SHOW ERROR
}
You can simply use includes and replace
First get the value of input element
Change to lowercase and check if both a and i exists or not
If exists replace a and i by respective values
function handleSubmit(e) {
e.preventDefault()
let element = document.getElementById('input').value
let lowerCased = element.toLowerCase()
if (lowerCased.includes('a') && lowerCased.includes('i')) {
console.log(element.replace(/a/gi, '#').replace(/i/gi, '!'))
}
}
<form onsubmit='handleSubmit(event)'>
<input id='input'>
<button type='submit'>Submit</button>
</form>

Remove special characters from input field

I've been searching everywhere but have been unable to find exactly what I am looking for.
I have an html form that is filled out with Mac addresses from our inventory so the strings inputted into the input field will look like:
A1:A2:A3:A4:A5:A6
I'm trying to write a script to remove the : character plus any spaces anywhere. That way when it is entered the output will be:
A1A2A3A4A5A6
This is what I have so far:
<input type="text" id="macaddress" onChange="removeChar();WriteLog();" />
Then in my script I have:
function removeChar() {
var a = document.getElementById("macaddress").value;
a = a.replace(/: /g, '');
document.getElementById.innerHTML = a;
}
I don't get any JavaScript errors with this but nothing happens.
I also have another script that pulls the value of the field into a work log which is the other function WriteLog().
Essentially I want to remove the : then have the new value pulled into the log by the second function.
If you want to keep only numbers and letts you can use this
a.replace(/[^a-zA-Z0-9]/g, '');
which basically replaces everything that isn't a-z or A-Z or 0-9 with an empty string.
A great tool for explaining regex and testing it is Regex101
And this line document.getElementById.innerHTML = a; should be fixed as well, you probably meant something like document.getElementById('some-elements-id').innerHTML = a;
Question spec says you want to remove : and : with space. Make the space in the regex optional:
a = a.replace(/:( )?/g, '');
But you also need to account for preceeding spaces:
a = a.replace(/( )?:( )?/g, '');
I would also trim the initial string (Just good practice)
a = a.trim().replace(/( )?:( )?/g, '');
Finally, I am not sure what this line does:
document.getElementById.innerHTML = a;, but that line will throw an error. Remove it.
to remove colons and spaces from string simply use
str = str.replace(/[:\s]/g, '');
HTML
<input type="text" id="macaddress"/>
<button onclick="removeChar()">Click me!</button>
JS
function removeChar() {
var a = document.getElementById("macaddress").value.trim();
a = a.split('');
a.forEach(function (character, index) {
if (character === ':') {
a.splice(index, 1);
}
});
a = a.join('');
document.getElementById("macaddress").value = a;
}
Your Regex searches for "colon immediately followed by space".
If you add a pipe in between them: /:| /, then it will search for all colons and/or spaces, in any order.
Demo:
function removeChar() {
var a = document.getElementById("macaddress").value;
a = a.replace(/:| /g, '');
document.getElementById("result").innerHTML = a;
}
<input type="text" id="macaddress" onChange="removeChar();" />
<div id="result"></div>

Replace multiple occurrences of a string (url) in a textarea

Probably I am not able to achieve this because I don't know much about regEx.
I have an array of unique links uniqueLinks.
Whenever those links appear in the HTML code I have my textarea, I want them to be replaced with {{tracking_link_N}} where N stands for the key. Right now I have the following function called when a button is pressed
function detect_links() {
var links = [];
var uniqueLinks = [];
var html = $("textarea[name=html]").val();
// Getting all the links in the textarea to replace them
$(html).find('a').each(function() {
links.push($(this).attr('href'));
})
// Creating an array of unique links uniqueLinks
$.each(links, function(i, el) {
if ($.inArray(el, uniqueLinks) === -1) uniqueLinks.push(el);
});
$.each(uniqueLinks, function(key, value) {
var newHTML = $("textarea[name=html]").val().replace(value, '{{tracking_link' + key + '}}');
$("textarea[name=html]").val(newHTML);
});
}
My textarea is:
<textarea name="html" class="form-control" rows="15"></textarea>
With this code so far it only replaces the first occurrence of the URL in the textarea. In some cases however the same URL appears multiple times in the textarea. E.g.
Google
Google 2
Google 3
My code returns
{{tracking_link0}}
{{tracking_link1}}
Google 3
It should return instead
{{tracking_link0}}
{{tracking_link1}}
{{tracking_link0}}
What I tried reading the other discussions is to change the replace() function like this
replace(/value/g, '{{tracking_link' + key + '}}');
But I don't get any appreciable result.
My URLs contain parameters as well, for example:
http://tracking.testapp.com/affil?offer=105&id=1152
Thanks for any help to address this issue.
PS: explaining the downvotes you give to questions makes them more believable
/value/g means to search for the exact string "value" globally. What you want is for it to search for the value of your value variable globally. For this, you must use RegExp() so that JavaScript parses value to mean the value of the variable value instead of the string "value".
var newHTML = $("textarea[name=html]").val().replace(new RegExp(escapeRegExp(value), "g"), '{{tracking_link' + key + '}}');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Add this somewhere in your JavaScript code (taken from this post):
escapeRegExp = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
Your issue is because the replace() method only works on the first found instance when you provide it a string value. Instead, if you give it a Regular Expression with the Global flag set (g) then it will find and replace all instances of the provided value.
Also note that you can make the code more succinct by passing a function to val(). Try this:
var uniqueLinks = ['http://google.co.uk', 'http://google.com'];
$.each(uniqueLinks, function(key, value) {
var re = new RegExp(value, 'gi');
$("textarea[name=html]").val(function(i, v) {
return v.replace(re, '{{tracking_link' + key + '}}');
});
});
textarea {
width: 100%;
height: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="html">Google
Google 2
Google 3
</textarea>
var uniqueLinks = ['http://google.co.uk', 'http://google.com'],
textArea=$("textarea[name=html]"),
text=textArea.text();
$.each(uniqueLinks, function(key, value) {
var re = new RegExp('"'+value+'">([^<]*)</',"g");
text=text.replace(re,'"'+value+'">{{tracking_link'+key+'}}<');
});
console.log(text);
textArea.text(text);
textarea {
width: 100%;
height: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="html">Google
Google 2
Google 3
</textarea>
This replace the text inside the links

Categories