I want to create a web-friendly image name from user input on a form. I want to replace any spaces in the user entered string with a dash as the user types.
My code only replaces the first space.
How do I replace all spaces with dashes?
$('#form_model').keyup(function(event) {
var newText = event.target.value;
newText = newText.replace(" ", "-");
$('#form_image').val(newText+".png");
});
You have to replace the spaces globally for all the occurrences. So, use this,
newText = newText.replace(/ /g, "-");
Final Code
$('#form_model').keyup(function(event) {
var newText = event.target.value;
newText = newText.replace(/ /g, "-");
$('#form_image').val(newText+".png");
});
This is easily done by using a regexpression with the g flag. g stand for global, so it affects the whole string and NOT only the first value.
Here is the working fiddle:
$('#form_model').keyup(function(event) {
var newText = event.target.value;
newText = newText.replace(/\s/g, "-");
$('#form_image').val(newText+".png");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="form_model" type="text">
<input id="form_image" type="text" readonly>
JS function replace() only replace the first character that matches. I usually use
.split('X').join('Y');
So, in your code it would be:
newText = newText.split(' ').join('-');
In this way, you can 'replace' all maching characters.
$(document).ready(function () {
$('#form_model').keyup(function(event) {
var newText = event.target.value;
newText = newText.replace(" ", "-");
$('#form_image').val(newText+".png");
});
});
Example is here: https://jsfiddle.net/55qxy624/
Related
I want to convert from utf-8 encoding to windows-1251 when the user enters text in the field
For example, the user enters: Äèíóàáó
I want to get: Aeioaao
I use a crutch of earth symbols, but I would like to find a normal method, I could not find anything working on the Internet.
What I use:
$(function(){
$('#txt').on('keyup paste change', function(){
var txt = $(this), val = txt.val();
val = val.replace(/[\u00c4]/g, 'A').replace(/[\u00e8]/g, 'e').replace(/[\u00ed]/g, 'i').replace(/[\u00f3]/g, 'o').replace(/[\u00e0]/g, 'a').replace(/[\u00e1]/g, 'a').replace(/[\u00e7]/g, 'c');
txt.val(val);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>paste: Äèíóàáó</p>
<input type="text" id="txt">
It helps me, because they use the same characters in the same way. But if it's new, you need to add it.
You should normalize the string using NFKD and then use regex to remove the diacritic group of chars.
$(function() {
$('#txt').on('keyup paste change', function() {
var txt = $(this),
val = txt.val();
val = val
.normalize("NFKD")
.replace(/\p{Diacritic}/gu, "")
txt.val(val);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>paste: Äèíóàáó</p>
<input type="text" id="txt">
With support for exceptions
If you want to support exceptions, you can first change those to something unique, then remove the diacritics and then bring back the exceptions.
Something like
const accentExceptions = [
{ char: 'Ä', uuid: crypto.randomUUID() },
{ char: 'ä', uuid: crypto.randomUUID() },
// crypto.randomUUID is not supported by all browsers so you
// might want to look for an alternative to creating some unique
// text/hash for each accented character
];
function encodeExceptions(value = '') {
let encoded = value;
accentExceptions.forEach(({ char, uuid }) => {
encoded = encoded.replace(new RegExp(char, 'g'), uuid);
});
return encoded;
}
function decodeExceptions(value = '') {
let decoded = value;
accentExceptions.forEach(({ char, uuid }) => {
decoded = decoded.replace(new RegExp(uuid, 'g'), char);
});
return decoded;
}
function removeDiacritics(value = '') {
return value
.normalize("NFKD")
.replace(/\p{Diacritic}/gu, "")
}
$(function() {
$('#txt').on('keyup paste change', function() {
var txt = $(this),
val = txt.val();
val = encodeExceptions(val);
val = removeDiacritics(val);
val = decodeExceptions(val);
txt.val(val);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>paste: Äèíóàáó</p>
<input type="text" id="txt">
How to format input text on html, sample input: Hi hello
I like to display the input like this
'Hi','hello',
When I hit enter, single quote with a comma will automatically display.
Any suggestion? Thank you.
The text is then formatted and returned to the input field. You only need an eventlistener, a function that converts the text.
const input = document.getElementById('watch');
input.addEventListener('keypress', function (e) {
e.preventDefault();
if (e.key === 'Enter') {
input.value = input.value.split(' ').map(s => `'${s}'`).toString() + ',';
}
return false;
});
<form>
<input type="text" value="Hi World" id="watch">
</form>
You can use split and join
const str = "Hi hello";
let output = '';
if(str)
output = `'${str.split(" ").join("','")}',`;
console.log(str);
const string = 'a b c'
console.log(string.split(' ').map(str => `'${str}'`).toString() + ',')
I am looking for a javascript where in I paste a content in textarea. The script must search for the timestamp of the format 01/07/2016 10:30:00 and chop it off. Please help me in this. It has a text content in which I have to eliminate the above thing. My html would be something like this-
<textarea id="quote" cols="50" rows="5" onkeyup="myFunction()">
</textarea>
<script>
function myFunction() {
var x = document.getElementById("quote");
x.value = x.value.toUpperCase();
}
</script>
This is a regex approach which solves your problem.
var txtArea = document.getElementById('mytextarea');
txtArea.addEventListener('paste', function(e) {
e.preventDefault();
e.stopPropagation();
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
var pattern = /[\d]{2}\/[\d]{2}\/[0-9]{4}\s[\d]{2}:[\d]{2}:[\d]{2}/g;
// remove date time pattern.
var newData = pastedData.replace(pattern, '');
// remove string 'LSDXW08'
newData = newData.replace(/LSDXW08/g, '');
// replace multiple spaces with 1 space
newData = newData.replace(/\s{2,}/g, ' ');
// append the value
txtArea.value = txtArea.value + newData;
});
<textarea id="mytextarea" rows="8" cols="70"></textarea>
<h4> !! Try paste this !! </h4>
<p>
I am looking for a javascript where in I paste a content in textarea. The script must search for the timestamp of the format 01/07/2016 10:30:00 and chop it off. Please help me in this. It has a text content in which I have to eliminate the above thing. My html would be something like this-
</p>
Try this regex
function myFunction() {
var x = document.getElementById("quote");
x.value = x.value.toUpperCase();
timestamp= x.value.match(/\d{2}\/\d{2}\/\d{4}\s\d{2}\:\d{2}\:\d{2}/g)
console.log(timestamp) //It will return array of timestamps found
}
I am trying to count the number of fullstops and commas in a sentence using a regex. The code I am using is the following.
var commaCount = $("#text-input").val().match(new RegExp(",", "g")).length;
var fullStopCount = $("#text-input").val().match(new RegExp(".", "g")).length;
This works for a comma count, however for the fullstop count it counts every character in the sentence. Can anyone explain why this is happening and how to fix it.
Please see below for the complete code:
var commaCount = $("#text-input").val().match(new RegExp(",", "g")).length;
var fullStopCount = $("#text-input").val().match(new RegExp(".", "g")).length;
$(".comma-count").text(", : " + commaCount);
$(".fullstop-count").text(". : " + fullStopCount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text-input" name="textarea" rows="5" cols="50">There should only be, one full stop.</textarea>
<p class="comma-count"></p>
<p class="fullstop-count"></p>
You need to escape . using \\, since . matches any single character except the newline character in regex.
var fullStopCount = $("#text-input").val().match(new RegExp("\\.", "g")).length;
or use regex like
var fullStopCount = $("#text-input").val().match(/\./g).length;
var commaCount = $("#text-input").val().match(new RegExp(",", "g")).length;
var fullStopCount = $("#text-input").val().match(new RegExp("\\.", "g")).length;
$(".comma-count").text(", : " + commaCount);
$(".fullstop-count").text(". : " + fullStopCount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text-input" name="textarea" rows="5" cols="50">There should only be, one full stop.</textarea>
<p class="comma-count"></p>
<p class="fullstop-count"></p>
Try below :
var fullStopCount = $("#text-input").val().match(new RegExp(/\./g)).length;
var commaCount = $("#text-input").val().match(new RegExp(/\,/g)).length;
Let's say I have a input field
<input type="text" class="form-control" name="filename">
and do write something like this:
Hällo
Is it possible to check while writing if that field has a the letter ä and change it to an a while writing ?
So far, I built this:
$search = array('ä', 'Ä');
$replace = array('ae', 'Ae');
$project = str_replace($search, $replace, $input);
You don't do this with PHP, you would do it with Javascript:
var el = document.getElementById("filename");
el.addEventListener('keyup', function(){
var replace = ['ä','å'];
var replacewith = 'a';
var replace1 = ['ö'];
var replacewith1 = 'o';
replace.forEach(function(letter){
el.value = el.value.replace(letter, replacewith);
});
replace1.forEach(function(letter){
el.value = el.value.replace(letter, replacewith1);
});
});
Add id="filename" to the input element for this to work. You can add as many letters to the replace array as you would like.
You can also add more arrays to replace letters.
https://jsfiddle.net/dek5as1x/1
Edit: Solution for several letters
var el = document.getElementById("filename");
el.addEventListener('keyup', function(){
var replaces = [['ä','å'],['ö','ø'],['ï','ì'],['ü','ù','û'],['ë','ê']];
var replacewith = ['a','o','i','u','e'];
replaces.forEach(function(letterGroup, index){
letterGroup.forEach(function(letter){
el.value = el.value.replace(letter, replacewith[index]);
});
});
});
Here you add a new array ([]) to replaces. Then you add all the letters to that array that should be turned into the same letter to that array. Example: ['ê','ë','è']. Then you add the letter to the replacewith array. It is important that the letter comes to replace the letters in the array has the same index as the corresponding array in replaces.
This solution should be a little cleaner for when you have lots of letters to replace.
You can't do this using PHP because PHP is serverside.
But you can do this using JavaScript.
Try:
<script language="JavaScript">
function replace() {
var input = document.getElementById("filename");
input.value = input.value.replace("ä","a");
}
<script>
<input type="text" class="form-control" name="filename" onchange="replace()">