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;
Related
This question already has answers here:
Find a string of text in an element and wrap some span tags round it
(6 answers)
Closed 2 years ago.
I created a simple regEx tester like this;
var expression = dialog.element.find(".input-regex");
var testString = dialog.element.find(".input-text");
var result = dialog.element.find(".output-text");
function highlight(e) {
debugger;
let searched = expression.val();
if (searched !== "") {
let text = $(".input-text").val();
let re = new RegExp(searched,"g");
let newText = text.replace(re, `<span style="background-color:yellow;">${searched}</span>`);
result.html(newText);
}
}
dialog.element.on("change",".input-regex",function(){
debugger;
var pattern = new RegExp(expression.val());
result.val(pattern.exec(testString.val()));
highlight();
});
Here's a Stack Snippet version of it:
var expression = $(".input-regex");
var testString = $(".input-text");
var result = $(".output-text");
function highlight(e) {
let searched = expression.val();
if (searched !== "") {
let text = $(".input-text").val();
let re = new RegExp(searched, "g");
let newText = text.replace(re, `<span style="background-color:yellow;">${searched}</span>`);
result.html(newText);
}
}
$(document.body).on("change", ".input-regex", function(event) {
var pattern = new RegExp(expression.val());
result.val(pattern.exec(testString.val()));
highlight();
});
<div>
<label>
Regex:
<br>
<input type="text" class="input-regex">
</label>
</div>
<div>
<label>
Text:
<br>
<input type="text" class="input-text">
</label>
</div>
<div>
Output:
<br>
<div class="output-text"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Its working for simple expressions, but when I use quantifiers it fails.
Any help is appreciated, I spent way too much time on this and still can't find the problem.
You're using the searched text in the yellow spans. Instead, use the text matched by the regular expression using the $& token with replace:
let newText = text.replace(re, `<span style="background-color:yellow;">$&</span>`);
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^
Live Example:
var expression = $(".input-regex");
var testString = $(".input-text");
var result = $(".output-text");
function highlight(e) {
let searched = expression.val();
if (searched !== "") {
let text = $(".input-text").val();
let re = new RegExp(searched, "g");
let newText = text.replace(re, `<span style="background-color:yellow;">$&</span>`);
result.html(newText);
}
}
$(document.body).on("change", ".input-regex", function(event) {
var pattern = new RegExp(expression.val());
result.val(pattern.exec(testString.val()));
highlight();
});
<div>
<label>
Regex:
<br>
<input type="text" class="input-regex">
</label>
</div>
<div>
<label>
Text:
<br>
<input type="text" class="input-text">
</label>
</div>
<div>
Output:
<br>
<div class="output-text"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If at some stage you want to color-code capture groups, their contents are available via $0, $1, etc. — although at that point you'd probably be better off using RegExp#exec and using the match information it provides, since that includes indexes.
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/
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
}
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()">
I am writing code to convert numbers counted in thousands (separated in writing in chunks of 3) into myriads (separated in writing in chunks of 4) for Japanese formatting.
the current code produces following results:
ex)
input: 123,456,789,123,456
output: 123兆4567億8912万3456
Using regular expressions I have been able to delete sequences of four 0's and the proceding character with myriad = myriad.replace(/0000\D/g, "");
result:
input: 12,300,002,345
output: 123億2345 (0000万 was deleted)
However, the code currently doesn't delete unnessecary zero's:
ex)
input: 32,131,200,232,132
output: 32兆1312億0023万2132
(I would like to delete the two zeros before 23万)
I am trying to find a regex solution to this and have attempted with myriad = myriad.replace(/?=0{1,3}/g, ""); to no avail... I am rather stumped, any suggestions would be helpful
EDIT:
I think the regex should replace 0's that follow any \D , but I can't figure out how to delete them without deleting the preceding character as well
EDIT: working app:
<!DOCTYPE html>
<html>
<head>
<title>変換天才</title>
<script>
//myriad converter function help from Stack Overflow user paxdiablo
function makeNum(num) {
num = num.replace(/,/g,""); //remove commas
var markers = "万億兆京該秭穣溝澗正載極";
var result = "";
//regroup in myriads
while (num.length > 4) {
if (markers.length == 0) {
result = "(?)" + num.substr(num.length-4) + result;
} else {
result = markers.substr(0, 1) + num.substr(num.length-4) + result;
markers = markers.substr(1);
}
num = num.substr(0, num.length-4);
}
return num + result;
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// insert commas for readability
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function makeCom(num){
num = num.replace(/,/g, "");
var result = num.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
return result;
}
function convert(){
var innum = document.getElementById("input").value;
var parsnum = (innum.replace(/,/g,""));
if (isNaN(parseInt(parsnum)) == true) {
document.getElementById("converted").innerHTML = "Please enter valid number.";
}
else {
var myriad = makeNum(innum);
// delete unnec. zeros
myriad = myriad.replace(/0000\D/g, "");
myriad = myriad.replace(/(\D)0+/g, "$1");
document.getElementById("converted").innerHTML = myriad ;
//display number with commas
var commanum = makeCom(innum);
document.getElementById("commaed").innerHTML = "You entered: " + commanum ;
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// button functions
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function multiplier(kake) {
var mult = document.getElementById("input").value;
if (mult == "") {
mult = kake;
}
else if (isNaN(mult)==false){
mult = (mult * kake);
}
else {
document.getElementById("converted").innerHTML = "Please enter valid number";
return;
}
document.getElementById("input").value = mult;
}
function thou(){
multiplier(1000);
}
function xMil(){
multiplier(1000000);
}
function xBil(){
multiplier(1000000000);
}
function xTril(){
multiplier(1000000000000);
}
function xQuad(){
multiplier(1000000000000000);
}
function clr(){
document.getElementById("input").value = "";
document.getElementById("converted").innerHTML = "";
}
</script>
</head>
<body>
<div><p>Enter a large whole number (commas OK). </p></div>
<input type="text" id="input"/>
<input type="submit" id="submit" value="Convert" onclick="convert()">
<br>
<input type="button" id="xthou" onclick="thou()" value="thousand">
<input type="button" id="xmil" onclick="xMil()" value="million">
<input type="button" id="xbil" onclick="xBil()" value="billion">
<br>
<input type="button" id="xtril" onclick="xTril()" value="trillion">
<input type="button" id="xquad" onclick="xQuad()" value="quadrillion">
<input type="button" id="clr" onclick="clr()" value="Clr">
<br><br>
<div><span id="commaed"></span></div>
<br>
<div id="converted"></div>
</body>
</html>
You need to use capturing group.
string.replace(/(\D)0+/g, "$1")
(\D) captures a non-digit character and the following 0+ would match one or more 0's. Replacing the matched chars with the chars present inside the group index 1 will give you the desired output.
I find regex fiddles very helpful for this kind of thing. I made one here:
https://regex101.com/r/jG3aB5/1
I think the regex that will solve your problem is this one:
(?:[^0-9])*(0*)
It matches an arbitrary number of zeros that follow a single non-digit character. The non-digit character is not captured and will not be replaced.
Another approach: Use lookbehind to not include the match character \D but match only zeros. Please see the working DEMO
/(?!\D)0+/g
In your case:
myriad = myriad.replace(/(?!\D)0+/g, "");