Remove extra white spaces from Array - javascript

The elements in my list should be
A1,A2,A3,A4
If user input A1,A2,A3,A4,,,,,,
or
A1,A2,,,A3,A4,,A5,,
or
A,B, ,, ,, V,,,, , , , , ,ddfd ,,,,,,,,
It should consider as
A1,A2,A3,A4
The logic written by me was
if(valueText !== null) { alert("Value Text..." + valueText);
valueList = valueText.split(",");
for (var i = 0; i < valueList.length; i++)
{
if (valueList[i] == "")
{
valueList.splice(i, 1);
alert("ValueList inside for if.."+valueList);
}
}
alert("ValueList.." + valueList);
}
But its not working properly

You can do something like this with match & join functions:-
var str = "A1,A2,,,A3,A4,,A5,,";
strnew = str.match(/[^ ,]+/g).join(',');
//Output--> A1,A2,A3,A4,A5
Hope this will help you...

You can do this with regex, for example:
var txt = 'A1,A2,,,A3,A4,,A5,,'
var res = txt.replace(/(,)\1*/g, ',').replace(/,$/, '');
//^ A1,A2,A3,A4,A5

Related

Highlight the textContent or innerText of an element containing other elements also based on user's searchedWords Using Pure Javascript

How to highlight all the words that the user is searching without affecting the text of the display and the attributes inside the elements. I have tried some approaches but there is a problem as described below. Please help. Thank you. Keep safe and healthy.
<input type='text' id='search' onkeyup="highlight(this.value)">
<p id='WE1'><b>WE</b>wE & theythem and We<span id="we2">we only.</span></p>
function highlight(searchedWords) {
var p = document.getElementById("WE1");
var words = searchedWords.trim().split(" ");
for (var i=0; i < words.length; i++) {
var word = words[i].trim();
/*
searchedWords = "We Only";
trial#1: use replaceAll
p.innerHTML = p.innerHTML.replaceAll(word, "<mark>" + word + "</mark>");
Issues:
1) replaceAll does not work in other browsers
2) It highlights also the tag attributes containing the searchedWords
3) It is case sensitive, it only highlights the exact match, though I've addressed this using this:
var str = p.innerHTML;
for (var j=0; j < words.length; j++) {
var x = words[j].trim(), string = str.toLowerCase();
while (string.lastIndexOf(x) > -1) {
str = str.substring(0, string.lastIndexOf(x)) + "<mark>"
+ str.substr(string.lastIndexOf(x), words[j].length) + "</mark>"
+ str.substring(string.lastIndexOf(x) + words[j].length, str.length);
string = string.substring(0, string.lastIndexOf(x));
}
}
p.innerHTML = str;
4) Changing .toLowerCase() also changes the display to lower case
var x = p.innerHTML.toLowerCase, word = word.toLowerCase;
p.innerHTML = x.replaceAll(word, "<mark>" + word + "</mark>");
trial#2:
p.innerHTML = p.innerHTML.replace(new RegExp(words[i], "gi"), (match) => `<mark>${match}</mark>`);
Issues:
1) OK, it is NOT case sensitive, it highlights all the searchedWords and the display is OK
2) But, it highlights also the tag attributes containing the searchedWord, anchor tags are affected
I tried also using p.childNodes, nodeValue, textContent so that the attributes
containing the searchedWord are not affected yet it only inserts the words
<mark>SearchedWord</mark> and the searchedWord is not highlighted.
*/
}
}
replaceAll is a new feature es2021. As for today it's incompatible with IE.
I found you something that might work. Please have a look and tell me if you still have problems How to replace all occurrences of a string in JavaScript on stackoverflow
I made a workaround by reading the innerHTML from right to left and disregarding the match if there is a "<" character to the left, which means that the match is inside a tag. Although the solution below seems to be manual, yet it works for me for now.
<!DOCTYPE html>
<html>
<input type="text" onkeyup="highlight(this.value)">
<p>Hi! I'm feeling well and happy, hope you too. Thank you.</p>
<p id="WE1"><b>WE</b> wE, We, we.
Only you.
<span id="wemark">mark it in your calendar.</span>
</p>
<script>
function highlight(searchedWords) {
var p = document.getElementsByTagName('p');
for (var i=0; i<p.length; i++) {
p[i].innerHTML = p[i].innerHTML.replace(new RegExp("<mark>", "gi"),(match) => ``);
p[i].innerHTML = p[i].innerHTML.replace(new RegExp("</mark>","gi"),(match) => ``);
}
var words = searchedWords.trim();
while (words.indexOf(" ") > -1) {words = words.replace(" "," ")}
if (!words) return;
words = words.split(" ");
for (var i = 0; i < p.length; i++) {
p[i].innerHTML = mark(p[i].innerHTML, words)
}
}
function mark(str, words) {
try {
for (var j=0; j < words.length; j++) {
var s = str.toLowerCase(),
x = words[j].toLowerCase().trim();
while (s.lastIndexOf(x) > -1) {
var loc = s.lastIndexOf(x), y = loc;
while (y > 0) {
y = y - 1;
if (s.substr(y,1)=="<"||s.substr(y,1)==">") break;
}
if (s.substr(y, 1) != "<") {
str = str.substring(0, loc) + "<mark>"
+ str.substr(loc, x.length) + "</mark>"
+ str.substring(loc + x.length, str.length);
}
s = s.substring(0, loc-1);
}
}
return str;
} catch(e) {alert(e.message)}
}
</script>
</html>

How to manipulate the characters written in a div to work with them afterwards using javascript

function doGetWord(){
var word = F.gword.value;
var wLength = word.length;
for(var i = 0; i < wLength; i++){
document.getElementById("dword").innerHTML += "_ "
}
}
This is a function that will write _ in a div in html, and what I want is to change them if the user types the corresponding input, for example if the first letter is supposed to be "a" then it would change the first _ to "a".
This is what I got so far:
function doGuessWord(){
dummy = F.t.value
if(dummy.length > 1){
dummy = ""
F.t.value = ""
}
for(var x = 0; x < wLength; x++){
if (substr(x, wLength) == dummy ) {
document.getElementById("dword").innerHTML += "_ "
}
else{
document.getElementById("dword").innerHTML += "dummy "
}
}
}
Could you help me out with this one?
Thanks in Advance!!
Something like this?
https://jsfiddle.net/9z66968a/3/
You will have to adapt it a bit. But you should be able to take the parseText function and pass it the params you need to return the text to insert where ever you want
There you go. I believe this is what you wanted. Feel free if you don't understand something
https://jsfiddle.net/vhsf8gpp/2/
var dashArr = [];
var dummyWord = document.getElementById('dummy');
var input = document.querySelector('input');
var counter = 0;
for(let i= 0; i<10;i++)
{
dashArr.push('_');
}
function WriteContent()
{
dummyWord.textContent = dashArr.map(d=>d).join(''); // This gets rid of the ',' inbetween the dashes
}
WriteContent();
//var charArr = [];
document.querySelector('input').addEventListener('keyup',function(){
var inputString = input.value;
dashArr[counter] = inputString.charAt(inputString.length - 1);
WriteContent();
counter++;
})
I used this post for reference.

Javascript Hangman - Replace Character In String

I've seen similar questions asked on Stack Overflow regarding this topic, but I haven't seen anything specific that would help me. My issue is that I can't seem to figure out how to replace a dash in hiddenWord with a correctly guessed letter while still retaining the dashes for un-guessed letters. Here is what I have so far and I'm not even sure if it's on the right track.
<script type="text/javascript">
// Declaration of Variables
var wordPool= ["Alf", "MarriedWithChildren", "Cheers", "MASH", "CharlesInCharge", "FmailyTies", "KnightRider", "MagnumPI", "MiamiVice"];
var lives = 6;
var myLetter;
var letter;
var wordChoice;
var hiddenWord;
var i;
var enter;
// Selects word randomly from wordPool[]. Then replaces the letters with "- ".
function selectedWord() {
var number = Math.round(Math.random() * (wordPool.length - 1));
wordChoice = wordPool[number];
for(i = 0; i < wordChoice.length; i++){
hiddenWord = wordChoice.replace(/./g,"- ");
}
console.log(hiddenWord);
}
// Gives myLetter a value of key pressed. If key is "Enter" selectedWord() initiates
document.onkeyup = function(event) {
var myLetter = event.key;
if(myLetter === "Enter"){
selectedWord();
}
console.log(myLetter);
}
</script>
I have seen some stuff with jQuery and PHP but I have to do it in javascript for class. Any help would be appreciated and if this has been addressed before please let me know.
You can check each character at the word string, compare it with the chosen character and replace it, if it is the same character.
I changed your code a bit to reflect what you are looking for.
Also make sure to lowercase all characters to make it easier for the player.
// Declaration of Variables
var wordPool= ["Alf", "MarriedWithChildren", "Cheers", "MASH", "CharlesInCharge", "FmailyTies", "KnightRider", "MagnumPI", "MiamiVice"];
var lives = 6;
var myLetter;
var letter;
var wordChoice;
var hiddenWord;
var i;
var enter;
// Change character to selected one
function checkCharacter(n) {
for(i = 0; i < wordChoice.length; i++){
console.log(wordChoice[i].toLowerCase() + "==" + n);
if(wordChoice[i].toLowerCase() == n.toLowerCase()){
hiddenWord = setCharAt(hiddenWord,i,n);
}
}
console.log("[" + hiddenWord + "]");
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
// Selects word randomly from wordPool[]. Then replaces the letters with "- ".
function selectedWord() {
var number = Math.round(Math.random() * (wordPool.length - 1));
wordChoice = wordPool[number];
hiddenWord = wordChoice.replace(/./gi,"-");
console.log(wordChoice + "[" + hiddenWord + "]");
}
// Gives myLetter a value of key pressed. If key is "Enter" selectedWord() initiates
document.onkeyup = function(event) {
var myLetter = event.key;
if(myLetter === "Enter"){
if(lives == 0){
selectedWord();
lives = 6;
}else{
lives--;
}
}
console.log(myLetter);
checkCharacter(myLetter);
}
//Select a random word at start
selectedWord();
I made a JSfiddle that is working and playable:
Check it out here...
Try
hiddenWord += "- "
Instead of replace
Or
hiddenWord += wordChoice[i].replace(/./g,"- ");
Here's an example:
var word = "do this";
var displayWord = [];
for (var i = 0; i < word.length; i++) {//build array
if (word[i] === " ") {
displayWord.push(" ");
} else {
displayWord.push("-");
}
}
function update(userGuess) {//update array
for (var i = 0; i < word.length; i++) {
if (word[i] === userGuess) {
displayWord[i] = userGuess;
} else {
displayWord[i] = displayWord[i];
}
}
}
//Guess letters
update("h");
update("o");
displayWord = displayWord.join('');//convert to string
alert(displayWord);
Check out the pen - https://codepen.io/SkiZer0/pen/VbQKPx?editors=0110

find exact value from user input to csv file content

I have a simple HTML file with input text id="ERP", I want the user to be able to find the exact match to the CSV file content. Here is the code I have been trying to fix. This searches the CSV file but returns result not exactly as the value entered from input box, Example, input box value = "CH-134", the out-put will show data for "CH-134-DT" how can I make the search result exactly the same as the input? Thank you in advance.
var DB = new Array();
function MakeDB() { DB = CSV.split('\n'); }
function CSVsearch(dbInfo) {
var posn = -1;
for (i=0; i<DB.length; i++) {
tmp = DB[i];
if (tmp.indexOf(dbInfo) != -1) { posn = i; break; }
}
if (posn == -1) { alert('No matching result from the file'); }
else { document.getElementById('tblDisplay').innerHTML = displayAsTable(DB[posn]); }
}
function displayAsTable(info) {
var table = '<table border="1" width="75%" bgColor="F5F5F5" borderColor="FFFFFF">';
var ary = info.split(',');
table += '<tr align="left"><th align="left">'+ary.join('</tr><th align="left">')+'</td></tr>';
table += '</table>';
return table;
}
function resetthis() {
document.getElementById("myForm").reset();
}
I think I would use the Javascript str.match(regexp) function and a regular expression, instead of using the str.indexOf(searchValue) function.
So in your case, I'd do something like:
var regex = '/\b' + dbInfo + '\b/g';
var matches = tmp.match(regex);
if (matches.length > 0)
{ ... }
Just replace the '\b' above with whatever you'd expect your incoming data to be separated by. For example, if you expect to find CH-134 is in your dataset with spaces before and after, you can leave the '\b' there. If it is in your dataset with commas, you can replace '\b' with ','. Or if you only know what terminates the word you're trying to match, you can leave off the first '\b' from the regex. For example, you could do something like:
//finds occurences of dbInfo with anything before it, but only a comma after it
var regex = '/' + dbInfo + ',/g';
//finds occurences of dbInfo with a word break before it, and no hyphen after it
var regex = '/\b' + dbInfo + '[^-]/g';
You'll probably be able to come up with a better, more precise, regular expression for your needs. My favorite site for playing with and testing out regular expressions is http://regexr.com/
Good luck!
tadaaa, as according to Seth, I added the dbInfo + ',' and simply put the 'while' so the loop wont stop when the search hits a similar value. WoohOooo
var DB = new Array();
function MakeDB() { DB = CSV.split('\n'); }
function CSVsearch(dbInfo) {
var posn = -1;
var input = document.getElementById('ERP').value;
for (i=0; i<DB.length; i++) {
tmp = DB[i]; //ROW DATA
while (tmp.indexOf(dbInfo+',') != -1) { posn = i; break; }
}
var data = DB[posn];
if (posn >=0) { (alert('RECORD FOUND!\nERP: ' + dbInfo));
document.getElementById('tblDisplay').innerHTML = displayAsTable(data); }
else { (alert ('NO RECORD FOUND')); }
}
function displayAsTable(info) {
var table = '<table border="1" width="75%" bgColor="F5F5F5" borderColor="FFFFFF">';
var ary = info.split(',');
table += '<tr align="left"><th align="left">'+ary.join('</tr><th align="left">')+'</td></tr>';
table += '</table>';
return table;
}
function resetthis() {
document.getElementById("myForm").reset();
}

Capitalise the first letter of each word within a certain class

Is it possible to capitalise the first letter of each word in a certain class name using jQuery / javascript? I just want to capitalise the first letter of each word of all the fields marked with the class 'capital'.
I just want it to do it as they type, and I know you can do it with css but this is no good as it is stored in the DB as lowercase still.
Here's a simple jQuery plugin that could do this for you:
$.fn.capitalise = function() {
return this.each(function() {
var $this = $(this),
text = $this.text(),
tokens = text.split(" ").filter(function(t) {return t != ""; }),
res = [],
i,
len,
component;
for (i = 0, len = tokens.length; i < len; i++) {
component = tokens[i];
res.push(component.substring(0, 1).toUpperCase());
res.push(component.substring(1));
res.push(" "); // put space back in
}
$this.text(res.join(""));
});
};
And then call like:
$(".myClass").capitalise();
Here's a working example.
The solution is something like this:
Working Sample: http://jsfiddle.net/Py7rW/7/
$('.captial').each(function(){
var arr = $(this).text().split(' ');
var result = "";
for (var x=0; x<arr.length; x++)
result+=arr[x].substring(0,1).toUpperCase()+arr[x].substring(1)+' ';
$(this).text(result.substring(0, result.length-1));
});
I think this will work :)
$('.capital').css("text-transform","capitalize");
You can try something like:
$('.capital').each(function() {
var s = $(this).text().split(' ');
for(var i=0; i<s.length; i++) {
s[i] = s[i].substring(0,1).toUpperCase() + s[i].substring(1);
}
s = s.join(' ');
$(this).text(s);
}
I would use the css text-transform:capitalize to avoid having to run this on every keypress,
and change the actual value of the fields on change.
field.value= field.value.replace(/((^| )[a-z])/g, function(a, b){
return b.toUpperCase();
});
Simple Step to capitalize the first letter of each word :
$(document).on('keyup', '#myText', function () {
this.value = this.value.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
});
You could do something like this. This will capitalize the text in a textbox whenever the text has changed:
$(document).ready(function() {
$('.capital').change(function() {
var arr = $(this).val().split(' ');
var result = "";
for (var i=0; i<arr.length; i++){
result += arr[i].substring(0,1).toUpperCase() + arr[i].substring(1);
if (i < arr.length-1) {
result += ' ';
}
}
$(this).val(result);
})
});
You can see a working fiddle here: http://jsfiddle.net/5dMg7/

Categories