Convert characters to asterisks in Javascript - javascript

Im trying to write a function that will convert all charactewrs after the first word into asterisks,
Say I have MYFIRSTWORD MYSECONDWORD, id want it to convert to asterisks on Keyup, but only for the second word, rendering it as so...
MYFIRSTWORD ***
I've been using the following only it converts each and every letter, is this possible?
$(this).val($(this).val().replace(/[^\s]/g, "*"));

I'm not sure about doing it with a single regex, but you can do this:
$("input").keyup(function() {
var i = this.value.indexOf(" ");
if (i > -1) {
this.value = this.value.substr(0, i)
+ this.value.substr(i).replace(/[\S]/g, "*");
}
});
Demo: http://jsfiddle.net/fc7ru/

<input type="text" onkeyup='$(this).val($(this).val().replace(/[^\s]/g, "*"));' />
Check in JsFiddle

you should try this code
var array = $(this).val().split(" ");
var newValue = "";
for(var i=0; i<array.length; i++) {
if ( i==0){
newValue = array[i];
continue;
} else{
newValue+= array[i].replace(/[^\s]/g, "*");
}
}
$(this).val(newValue);

Related

How can I add minus sign in jquery?

My html code :-
<input type="text" id="test">
<span class="display"></span>
My jquery code :
$("#test").keyup(function(e){
$('span.display').text(formatCurrency($(this).val()));
this.value = this.value.replace(/[^0-9\.]/g,'');
});
Demo and full code is like this : https://jsfiddle.net/oscar11/nbLbb037/
I want the input text can enter this : -10000000
And the result who displayed in class display is : -10.000.000
How can I add minus (-) sign?
Need to change code like below:-
output = output.reverse();
if(output[1] == '.'){
output.splice(1, 1);
formatted = output.join("");
}else{
formatted = output.join("");
}
And every thing will be fine.
Example:-
$("#test").keyup(function(e){
$('span.display').text(formatCurrency($(this).val()));
this.value = this.value.replace(/[^0-9\.-]/g,'');
});
// format currency on pagu and revisi
var formatCurrency = function(num){
var str = num.toString().replace("$", ""), parts = false, output = [], i = 1, formatted = null;
if(str.indexOf(",") > 0) {
parts = str.split(",");
str = parts[0];
}
str = str.split("").reverse();
for(var j = 0, len = str.length; j < len; j++) {
if(str[j] != ".") {
output.push(str[j]);
if(i%3 == 0 && j < (len - 1)) {
output.push(".");
}
i++;
}
}
output = output.reverse();
if(output[1] == '.'){
output.splice(1, 1);
formatted = output.join("");
}else{
formatted = output.join("");
}
return(formatted + ((parts) ? "," + parts[1].substr(0, 1) : ""));
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test">
<span class="display"></span>
adding a minus sign is very easy, just replace
this.value = this.value.replace(/[^0-9\.]/g,'');
with following
this.value = this.value.replace(/[^0-9\.-]/g,'');
updated js fiddle is https://jsfiddle.net/nbLbb037/3/
But. You need to use regular expression test to verify exact currency test. Try exploring js regular expression test for your "formatCurrency" function. Of course thats purly upto you. Current solution will let you move further.
I have updated the regular expression js code on fiddle. Refer to https://jsfiddle.net/nbLbb037/5/

Javascript Higher Order Functions and DOM

I am working on a project that takes text that a user inputs in a text box and returns the most common word.
Javascript:
var bestMode = 1;
var currentMode = 0;
var character;
function Find_Word(){
var words = document.getElementById('words').innerText;
var punctuationless = words.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
var WordList = finalString.split(" ");
return FindMode(WordList);
}
function FindMode(WordList){
for(var i=0; i<WordList.length; i++){
for(var m=i; m<WordList.length; m++){
if(WordList[i] == WordList[m]){
currentMode += 1;
}
if(bestMode<currentMode){
bestMode = currentMode;
character = WordList[i];
}
}
currentMode = 0;
}
}
console.log(bestMode);
HTML:
<html>
<body>
<h1>Most common word used</h1>
<input type="text" id="words" rows="10" columns="30"></input>
<button type="button" id="FindWord" onclick="Find_Word()">Find Word</button>
<script src="CommonWord.js"> </script>
</body>
</html>
What I can't figure out is the correct way to pull text from the text box into a variable as one string. My function Find_Word takes the received string when the button is pressed and strips away punctuation and leaves an array WordList with with each individual word in the string.
After that, I also can't understand how to pass that array into my second function findMode where I iterate through each value of the array to find the most common word. That is saved in the variable bestMode.
It looks as if you are both getting the current text and passing the array correctly (although perhaps you should get the textbox value using the .value property). What problem are you having exactly? I am not sure what FindMode is supposed to do either.
Here is some script that is based on what you posted that sorts "words" according to how often they appear :
(function(w) {
w.Sort_Words = function(words) {
var o = {}, l = [];
for(var i=0; i<words.length; i++) {
if (typeof o[words[i]] === 'undefined') {
o[words[i]] = 0;
l.push(words[i]);
}
o[words[i]] ++;
}
l.sort(function(a, b) { return o[b] - o[a]; });
return l;
};
w.Find_Word = function() {
var text = document.getElementById('words').value;
var words = text.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"").replace(/\s{2,}/g," ").split(' ');
var sorted = w.Sort_Words(words);
document.getElementById('results').innerText = sorted.length === 0 ?
'You must type at least one word' :
'The most commonly used word was: ' + sorted[0];
};
})(window);
Fiddler: http://jsfiddle.net/4u1mv20h/4/

Replace a space within a SPAN tag with a BR tag

I need to replace the space between the 2 words with a BR tag. I've tried quite a few things, this one I thought would work, but the original script only does it to the first item. :( I need it to replace it on all the menu items.
It's for menu text on a CMS, so I won't know what the text is going to be. All I know is that it will always be no more than 2 words.
I can use either JS or jQuery.
Demo here: JS Bin Link
HTML:
<span class="navtext">Lorem ipsum</span>
<br>
<span class="navtext">Lorem ipsum</span>
<br>
<span class="navtext">Lorem ipsum</span>
JavaScript:
// Doesnt work
// var span = document.getElementsByTagName(".navtext");
// Only works for the first one
var span = document.querySelector(".navtext");
// Doesnt work
// var span = document.querySelectorAll("navtext");
function space() {
var elem = document.createElement("br");
// elem.className = "space";
// elem.textContent = " ";
return elem;
}
function replace(elem) {
for(var i = 0; i < elem.childNodes.length; i++) {
var node = elem.childNodes[i];
if(node.nodeType === 1) {
replace(node);
} else {
var current = node;
var pos;
while(~(pos = current.nodeValue.indexOf(" "))) {
var next = current.splitText(pos + 1);
current.nodeValue = current.nodeValue.slice(0, -1);
current.parentNode.insertBefore(space(), next);
current = next;
i += 2;
}
}
}
}
replace(span);
I think, you dont want to use jQuery. Well, Here is quick solution:
var elms = document.querySelectorAll(".navtext");
for(var i=0; i<elms.length; i++){
elms[i].innerHTML = elms[i].innerHTML.replace(/\s/gi, "<br />");
}
Here is the jsfiddle: http://jsfiddle.net/ashishanexpert/NrTtg/
using jQuery you can do this:
$("span.navtext").each(function(){
$(this).html($(this).text().replace(/ /g,"<br />"));
})
If you install jQuery you can make it all more simple. Follow the installation instructions and then the code you'll need is something like:
jQuery(function($) {
// for each navtext run the described function
$(".navtext").each(function() {
// "this" represents the navtext
// replace all " " with "<br/>" from this's html
var code = $(this).text();
code = code.replace(" ", "<br/>");
// update this's html with the replacement
$(this).html(code);
});
});
Someone on twitter provided me with a fix, which was exactly like what Ashish answered.
var spans = document.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
spans[i].innerHTML = spans[i].innerHTML.replace(' ', '<br>');
}
But that would quite work for me, but it did give me my answer! So thanks to Pete Williams
This is the code I went with:
var spans = document.querySelectorAll('.navtext');
for(var i = 0; i < spans.length; i++) {
spans[i].innerHTML = spans[i].innerHTML.replace(' ', '<br>');
}

AppendTo previous iteration (each)

I have the following code, which should split this string #266##271##295# into this
266
271
295
and append it to the same container where it came from: .groups
$('.groups').each(function(){
var str = $(this).html();
if (str.substring(0, 1) == '#') {
str = str.substring(1); // Remove first #
}
if(str.substring(str.length-1, str.length) == '#'){
str = str.substring(0, str.length-1); // Remove last #
}
str = str.split(/[##]+/);
$(this).empty(); // empty the groups container
$.each(str, function(index, val){
alert(val);
var html = '' + val + ''
$(html).appendTo(this);
});
});
My problem (i think) is the line $(html).appendTo(this);
i somehow need to add it to the previous each().
How can I do this. Or am I moving in the wrong direction with this code?
I think you made this way too complicated, just do this:
var str = $(this).html();
var parts = str.split("#");
var html = "";
for (var i = 0; i < parts.length; i++) {
html += '' + parts[i] + '';
}
$(this).append(html);
Something like this?
$('.groups').each(function(){
var str = $(this).html();
if (str.substring(0, 1) == '#') {
str = str.substring(1); // Remove first #
}
if(str.substring(str.length-1, str.length) == '#'){
str = str.substring(0, str.length-1); // Remove last #
}
str = str.split(/[##]+/);
$(this).empty(); // empty the groups container
var target = $(this);
$.each(str, function(index, val){
alert(val);
var html = '' + val + ''
$(html).appendTo(target);
});
});
I added the var target = $(this) outside your second loop as a reference that you can use inside your second loop.
You do need to be mindful of the leading and trailing #'s, but you can easily trim them while you split with a clever regex. When you use $.each to iterate over an array, the this reference no longer refers to your original context but to the current item. Constructing the item's markup and concatenating to a string which you insert outside of the loop will not only get around this, but also provide better performance since you will only be doing one DOM insertion.
$('.groups').each(function(){
var str = $(this).html();
str = str.replace(/^#+|#+$/g, ''); // trim leading and trailing #
var links = str.split("#");
var markup = '';
$.each(links, function(){
markup += '' + this + "\n";
});
$(markup).appendTo(this);
});

Counting and limiting words in a textarea

I managed to make this little jquery function to count the number of words entered in textarea field.
here is the fiddle
and here is the code:
JQUERY:
$(document).ready(function()
{
var wordCounts = {};
$("#word_count").keyup(function() {
var matches = this.value.match(/\b/g);
wordCounts[this.id] = matches ? matches.length / 2 : 0;
var finalCount = 0;
$.each(wordCounts, function(k, v) {
finalCount += v;
});
$('#display_count').html(finalCount);
am_cal(finalCount);
}).keyup();
});
and here is html code
<textarea name="txtScript" id="word_count" cols="1" rows="1"></textarea>
Total word Count : <span id="display_count">0</span> words.
how can i make modifications in it to have the output like this
Total word Count : 0 words. Words left : 200
and when it reach 200 words it shall not allow to either paste, or type more words in the textarea field, in jquery? i.e. it shall restrict user to type exactly 200 words not more than that.
Please help.
Thanks a lot in advance.
EDIT: The modification is needed in this code only, as i am very well aware of the plugins, but they may interfere with the main code.
Using return false to stop keyup events doesn't block the event, because in this case the event has already fired. The keyup event fires when the user releases a key, after the default action of that key has been performed.
You will need to programmatically edit the value of the textarea you have as #wordcount:
$(document).ready(function() {
$("#word_count").on('keyup', function() {
var words = 0;
if ((this.value.match(/\S+/g)) != null) {
words = this.value.match(/\S+/g).length;
}
if (words > 200) {
// Split the string on first 200 words and rejoin on spaces
var trimmed = $(this).val().split(/\s+/, 200).join(" ");
// Add a space at the end to make sure more typing creates new words
$(this).val(trimmed + " ");
}
else {
$('#display_count').text(words);
$('#word_left').text(200-words);
}
});
});
http://jsfiddle.net/k8y50bgd/
I would do it like this ?
$("#word_count").on('keydown', function(e) {
var words = $.trim(this.value).length ? this.value.match(/\S+/g).length : 0;
if (words <= 200) {
$('#display_count').text(words);
$('#word_left').text(200-words)
}else{
if (e.which !== 8) e.preventDefault();
}
});
FIDDLE
A simple plugin can be found here:
Simple Textarea Word Counter using jQuery
Adding a simple if condition will solve your problem.
$.each(wordCounts, function(k, v) {
if(finalCount <= 200) {
//Todos
}
else {
return false; //prevent keyup event
}
});
$(document).ready(function(){
$("textarea").on('keyup',function(){
var value = $('textarea').val();
var wordCount = 0;
if(value == ""){
$('textarea').empty();
}
else{
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
}
if(wordCount > 25){
var trimmed = $(this).val().split(/\s+/,25).join(" ");
$(this).val(trimmed + " ");
}
else{
$('#display_count').html(25- wordCount +" words left");
}
});
});
You can use positive lookahead regexes to preserve the whitespace - so that returncodes and tabs are not collapsed to a single space. Something like this:
var wordLimit = 5;
var words = 0;
var jqContainer = $(".my-container");
var jqElt = $(".my-textarea");
function charLimit()
{
var words = 0;
var wordmatch = jqElt.val().match(/[^\s]+\s+/g);
words = wordmatch?wordmatch.length:0;
if (words > wordLimit) {
var trimmed = jqElt.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = jqElt.val()[trimmed.length];
jqElt.val(trimmed + lastChar);
}
$('.word-count', jqContainer).text(words);
$('.words-left', jqContainer).text(Math.max(wordLimit-words, 0));
}
jqElt.on("keyup", charLimit);
charLimit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container">
<textarea class="my-textarea"></textarea>
<span class="words-left"></span> words left
<div>
Here is the final solution.
(function(){
$("textarea").after("<p>Number of words: <span class='count'>0</span>/10</p>");
$("textarea").keypress(function(){
var words = $.trim($(this).val()).split(" ").filter(function(word){
return $.trim(word).length > 0
});
var wordlength = words.length;
$(".count").text(wordlength);
if(wordlength > 10){
alert("Please do not enter more than 10 words");
$(this).val( words.splice(0,10).join(" "));
return false;
}
})
})

Categories

Resources