Get the value discarding the marker in JavaScript by substring - javascript

In an implementation I am fetching list of values by doing substring.
For example below are list of values:
First list item = 'itemno1',second list item = 'itemno2',third list item = 'itemno3 ****disabled****'.
I am using a marker disabled to identify the value as a disabled one. So, when the user
adding a value, I am just appending a space and then appending the marker disabled after that. But while updating I want to discard the marker and only get the value.
So, I am using the function below:
function GetAppropriateListValue(listVal) {
return listVal.substring(0, Math.max(0, listVal.lastIndexOf(" ")) || Infinity);
}
The function above discards the rest of characters after the first space character.
But, in some other scenario, user can add an item with multiple spaces.
'itemno10 itemno10 ****disabled****'
Here I need to get the value after discarding the marker ****disabled****
How can I achieve this in JavaScript?
Thanks.

var str = 'itemno10 itemno10 *disabled*'
str = str.replace('*disabled*',""); // returns 'itemno10 itemno10 '

Not pretty but if you want a substring then
var s='itemno10 itemno10 *****disabled****';
var t='itemno11 itemno11';
s = s.slice(0,(s.indexOf(' *')!== -1)? s.indexOf(' *'):undefined);
t = t.slice(0,(t.indexOf(' *')!== -1)? t.indexOf(' *'):undefined);
alert(s + " " + t);

Related

Plucking specific substring from string - Javascript

I have a dynamic string that is generated like one of the following:
var q = "FROM Table SELECT avg(1), avg(2), avg(3) where x='y'
var q = "SELECT avg(1), avg(2), avg(3) FROM Table where z='x' since x days ago
The values after the select are also dynamic where there could be 1 select option, or 10. I'm trying to create some logic to always pluck whatever is selected into an array, but having trouble dealing with the dynamic nature (string being constructed dynamically AND the # of selects being dynamic).
Basically, end result something like this:
['avg(1)', 'avg(2)', 'avg(3)']
Currently I'm doing something like the following, but it always expects the string to be formatted in a certain order (always starting with SELECT and where after the fields to pluck):
let splitQ = q.match(".*SELECT(.*)where");
let selects = splitQ[1].trim().split(",");
Here is a working solution.
It makes these assumptions about the query (after lowercased).
the values come after the first instance of the word 'select '
if the query starts with 'from', values end before the first instance of ' where'
if the query starts with 'select', values end before the first instance of ' from'
const test1 = "FROM Table SELECT avg(1), avg(2), avg(3) where x='y'";
const test2 = "SELECT avg(1), avg(2), avg(3) FROM Table where z='x' since x days ago";
function extractValues(query) {
// in both scenarios, the values always come directly after 'select '
const valuesComeAfterMe = 'select ';
query = query.toLowerCase();
let valuesEndBeforeMe;
// conditionally handle both query syntaxes
if (query.startsWith('from')) {
valuesEndBeforeMe = ' where';
} else if (query.startsWith('select')) {
valuesEndBeforeMe = ' from';
} else {
throw Error('query not handled');
}
// remove start
query = query.slice(query.indexOf(valuesComeAfterMe) + valuesComeAfterMe.length);
// remove end
query = query.slice(0, query.indexOf(valuesEndBeforeMe));
// split values and trim whitespace
return query.split(',').map(item => item.trim());
}
console.log(extractValues(test1));
console.log(extractValues(test2));

Look for substring in a string with at most one different character-javascript

I am new in programing and right now I am working on one program. Program need to find the substring in a string and return the index where the chain starts to be the same. I know that for that I can use "indexOf". Is not so easy. I want to find out substrings with at moste one different char.
I was thinking about regular expresion... but not really know how to use it because I need to use regular expresion for every element of the string. Here some code wich propably will clarify what I want to do:
var A= "abbab";
var B= "ba";
var tb=[];
console.log(A.indexOf(B));
for (var i=0;i<B.length; i++){
var D=B.replace(B[i],"[a-z]");
tb.push(A.indexOf(D));
}
console.log(tb);
I know that the substring B and string A are the lowercase letters. Will be nice to get any advice how to make it using regular expresions. Thx
Simple Input:
A B
1) abbab ba
2) hello world
3) banana nan
Expected Output:
1) 1 2
2) No Match!
3) 0 2
While probably theoretically possible, I think it would very complicated to try this kind of search while attempting to incorporate all possible search query options in one long complex regular expression. I think a better approach is to use JavaScript to dynamically create various simpler options and then search with each separately.
The following code sequentially replaces each character in the initial query string with a regular expression wild card (i.e. a period, '.') and then searches the target string with that. For example, if the initial query string is 'nan', it will search with '.an', 'n.n' and 'na.'. It will only add the position of the hit to the list of hits if that position has not already been hit on a previous search. i.e. It ensures that the list of hits contains only unique values, even if multiple query variations found a hit at the same location. (This could be implemented even better with ES6 sets, but I couldn't get the Stack Overflow code snippet tool to cooperate with me while trying to use a set, even with the Babel option checked.) Finally, it sorts the hits in ascending order.
Update: The search algorithm has been updated/corrected. Originally, some hits were missed because the exec search for any query variation would only iterate as per the JavaScript default, i.e. after finding a match, it would start the next search at the next character after the end of the previous match, e.g. it would find 'aa' in 'aaaa' at positions 0 and 2. Now it starts the next search at the next character after the start of the previous match, e.g. it now finds 'aa' in 'aaaa' at positions 0, 1 and 2.
const findAllowingOneMismatch = (target, query) => {
const numLetters = query.length;
const queryVariations = [];
for (let variationNum = 0; variationNum < numLetters; variationNum += 1) {
queryVariations.push(query.slice(0, variationNum) + "." + query.slice(variationNum + 1));
};
let hits = [];
queryVariations.forEach(queryVariation => {
const re = new RegExp(queryVariation, "g");
let myArray;
while ((searchResult = re.exec(target)) !== null) {
re.lastIndex = searchResult.index + 1;
const hit = searchResult.index;
// console.log('found a hit with ' + queryVariation + ' at position ' + hit);
if (hits.indexOf(hit) === -1) {
hits.push(searchResult.index);
}
}
});
hits = hits.sort((a,b)=>(a-b));
console.log('Found "' + query + '" in "' + target + '" at positions:', JSON.stringify(hits));
};
[
['abbab', 'ba'],
['hello', 'world'],
['banana', 'nan'],
['abcde abcxe abxxe xbcde', 'abcd'],
['--xx-xxx--x----x-x-xxx--x--x-x-xx-', '----']
].forEach(pair => {findAllowingOneMismatch(pair[0], pair[1])});

Javascript prepend to line in textarea on double click

What I am trying to do:
Double click a line in a textarea.
Prevent text from being selected.
Prepend a dash to that line.
I know some basic jquery but can't seem to understand the lower level javascript that is required. Here is what I have so far:
$("textarea").dblclick(function() {
//TODO: Prevent selection
//TODO: Get the line number??
//TODO: prepend a dash to the line
// or replace the line with itself
// plus the dash at the front??
});
Here is the fiddle.
There may be a number of things you need to do, but something like this should be enough to get you started:
$("textarea").dblclick(function() {
//first, get the position of the cursor
var cursorPosition = $(this).prop("selectionStart");
//get the text value at the cursor position
var textValue = $(this).val().substr(cursorPosition,1);
//use a loop to look backward until we find the first newline character \n
while(textValue != '\n' && cursorPosition >= 0) {
cursorPosition--;
textValue = $(this).val().substr(cursorPosition,1);
}
//update the textarea, combining everything before the current position, a dash, and everything after the current position.
$(this).val(($(this).val().substr(0,cursorPosition+1) + '-' + $(this).val().substr(cursorPosition+1)))
});
You can see an example in this JS Fiddle:
http://jsfiddle.net/igor_9000/4zk5otvm/2/
There will probably be a lot more you need to add to this, depending on what you want to be able to do with the function and what limits you want to enforce, but that should be enough to get you started. Hope that helps!
I needed something similar, here's what you might've been looking for with vanilla JS (without jQuery or anything):
function dblClickEvt(obj) {
let pos = obj.selectionStart;
let text = obj.value;
let lineStart = text.lastIndexOf("\n", pos);
let lineEnd = text.indexOf("\n", pos);
let before = ( lineStart === -1 ? '' : text.slice(0, lineStart + 1) ); // row(s) before incl. line break
let after = '';
if(lineEnd === -1) // -> last row is selected
lineEnd = undefined; // because -1 would cause the selection to strip the last character
else
after = text.slice(lineEnd); // row(s) after the selection
let selected = text.slice(lineStart + 1, lineEnd); // the selected row
// write new value (manipulate before, selection a/o after if you want)
obj.value = before + '-' + selected + after;
// reset cursor position:
obj.selectionStart = pos;
obj.selectionEnd = pos;
}
Use the "ondblclick" attribute of your textarea to call the function:
<textarea ondblclick="dblClickEvt(this)"></textarea>
This only supports modern browsers, if you want to support older browsers, then you need to get the method that calculates selectionStart. This is not fully tested and if you double click on a line that is selected, it toggles the dash. And when you set the new value, the selection goes away.
$("textarea").on("dblclick", function (evt) {
var taValue = this.value;
//if there is no text than there is nothing to do
if(!taValue.length) return;
//get the position of the selection (not supported old browsers)
var se = this.selectionStart;
//find where the previous line break is located (array lastIndexOf not supported old browsers)
//thinking about it, probably do not need to split... :)
var loc = taValue.substr(0, se).split("").lastIndexOf("\n")+1;
//separate the text by characters
var parts = taValue.split("");
//if the character is a -, than remove it
if (parts[loc]==="-") {
parts.splice(loc, 1);
} else { //else inject the -
parts.splice(loc, 0, "-");
}
//join the array back up into a string and set the value
this.value = parts.join("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows=10 cols=30>FOO FOO FOO
BAR BAR BAR
CAKE CAKE CAKE
WORLD WORLD WORLD</textarea>

Adding percentage to a price field incl. currency code

I'm trying to add 10% to a price field via javascript and so far i haven't been able to, and was hoping you guys would be able to help.
The field incl. currency code etc.
I did try something in this direction:
<script type="text/javascript">
$( document ).ready(function() {
var Total = $("#cashamount");
Total.val(Total.val() * 1.1);
});
</script>
But that didn't work ;(
The price field shows up like the following.
<span id="cashamount" class="additional xxlarge carrental_total_amount">48,300.00 ISK</span>
After adding the 10% to the price, it should say in this example:
<span id="cashamount" class="additional xxlarge carrental_total_amount">53,130.00 ISK</span>
Any ideas are welcome, and i would really appreciate help on this matter as i do think it's fairly simple but i'm not very well into Javascripting.
First this: (solution below)
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of elements, the
.val() method returns an array containing each selected option; if no
option is selected, it returns null, jQuery docs
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method. To get the value of a script element, use the .html() method,
jQuery docs
So, one solution would be next:
var Total = $("#cashamount");
var totalNumber = Number(Total.text().replace(/[^0-9\.]+/g,""));
Total.text((totalNumber * 1.1).toFixed(2));
//Add currency to this
Here's JsFiddle
var x = $("#cashamount").html(); // Fetching the value
var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
var newAmmt = intAmmt*1.1; // Incrementing by 10%
var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
$("#cashamount").html(y); // Setting the html;
So you can create a function for this:
function updateVal(elem){
var x = elem.html(); // Fethching the value
var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
var newAmmt = intAmmt*1.1; // Incrementing by 10%
var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
elem.html(y); // Setting the html;
}
and use it as:
$(document).ready(function(){
updateVal($("#cashamount"))
});

jQuery check is letter is available in the array

I still have a problem with jQuery code.
I want to check characters from strings which is in array while user typing something in the input. If any of first one characters is available in the array i want to display "VALID".
var postcodes = ["00-240","80","32","90","91", "8", "11"];
$('input[name="text-391"]').keyup(function(){
var val = this.value;
var m = $.map(postcodes,function(value,index){
var reg = new RegExp('^'+val+'.*$')
return value.match(reg);
});
if(m.length && val.length) {
$('#error').hide(300);
} else {
$('#error').show(300);
}
});
This code checks that all what user type in the input is in array, but i want to check this letter after letter.
For example:
user types: 0 - it's ok
user types: 00 - it's still ok
user types 00-340 - it's not ok and now I want to display warning that we haven't it in the array
user types: 3 - it's ok
user types: 35 - it's not ok, and now i want to display warning that we haven't it in the array
user types 80-125 - it's still ok [important]
user types 11-1 - it's still ok [important]
I will be very grateful for any tips. Regards
you need to add below code in $.map
if(val.length>2 && val.indexOf("-")>-1 && !(value.indexOf("-")>-1))
val= val.substring(0,val.indexOf("-"))
Here is the working DEMO
Explanation:
You just want to check if enter value length is more than two and it contains - and value in map should not contain -(you need last and condition for letter like "xx-xxx"
Thanks
You'll have to check it both ways:
var m = $.map(postcodes,function(value,index){
var reg = new RegExp('^'+val+'.*$')
var result=value.match(reg);
if (result.length) {
return result;
} else {
reg = new RegExp('^'+value+'.*$')
return val.match(reg);
}
});
You can optimize further if you first create an array of regex's based on postcodes and then reference them by index in the callback function.

Categories

Resources