How do you put the last character 1st in a string [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The R is displaying last in the string initially it must display first how can I put the last character before the number value in the string so that it can display at the beginning of the value
contentHtml +=
"<td rowspan1=\"" + 1 + "\" class=\"" + (rowspan !== "" && rowspan > 1 ? "groups" : "") + " " + (!isNaN(value) || (!isNaN(value.toString().substr(1, value.length)) || value == "N/A" || value.length < 7 && value.toString().substr(value.length - 1) == '%') ? "text-center" : "text-left") + "\">" + value + (!isNaN(value) ? preFix : "") + color + (!isNaN(value) ? postFix : "") + "</td>";
if (rowspan > 1) {
var rowspanContent = "<td rowspa1=\"" + rowspan + "\" class=\"" + (rowspan !== "" && rowspan > 1 ? "groups" : "") + " " + (!isNaN(value) || (!isNaN(value.toString().substr(1, value.length)) || value == "N/A" || value.length < 7 && value.toString().substr(value.length - 1) == '%') ? "text-center" : "text-left") + "\">" + value + (!isNaN(value) ? preFix : "") + color + (!isNaN(value) ? postFix : "") + "</td>";
}

If you want o swap the numbers and letters you should see Nina Scholz answer.
If you just want to put the last character first you can do it like this:
function lastToFirst(value){
return value.slice(-1) + value.substring(0,value.length-1);
}
or even cleaner
function lastToFirst(value){
return value.slice(-1) + value.slice(0,-1);
}

You could use a regular expression and swap numbers and letters (not numbers).
function swap(s) {
var m = s.match(/^(\d+)(\D+)$/);
return m[2] + m[1];
}
console.log(swap('1234R'));
Otherwise, you could change your code from
value + (!isNaN(value) ? preFix : "") + color + (!isNaN(value) ? postFix : "")
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
to
(!isNaN(value) ? preFix : "") + value + color + (!isNaN(value) ? postFix : "")
//^^^^^^^^^^^^^^^^^^^^^^^^^^^
and use preFix instead of postFix.

Direct answer is:
var value ="1234567R";
var res = "R" + value.split("R")[0];
alert(res);

Without code, it's compicated to help.
If just you want to put the last x chars to first, here is a little piece of code
var nb = 1;
var s = "123456789R";
var last = s.split(s[s.length - (nb - 1)])[1];
var s1 = s.slice(0, s.length - nb);
s = last + s1;
//s => "R123456789"

Related

How to get Google meet link thru google calendar api in javascript?

I want to create a line notify which can send the event detail from my google calendar everyday.
I can get the title, description, location...etc, but I don't see the conference data in calendar API.
I use Google Apps Script to run the code.
Here is my code.
const Now = new Date();
const Start = new Date(new Date().setHours(0, 0, 0, 0));
const End = new Date(new Date().setHours(23, 59, 59, 999));
const calendarData = calendar.getEvents(Start, End);
function Notify() {
var NotifyContents = '';
var i = 1;
calendarData.forEach(item =>{
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i+". "+ item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n": "";
NotifyContents += (item.getconferencedata() != "") ? ("\n" + i+". "+ item.getconferencedata()) : ("No Conference\n");
i++;
}
}
)
if (typeof NotifyContents === 'string' && NotifyContents.length === 0) {
return;
}
NotifyTokens.forEach(function(value){
UrlFetchApp.fetch("https://notify-api.line.me/api/notify", {
"method" : "post",
"payload" : {"message" : NotifyContents},
"headers" : {"Authorization" : "Bearer " + value}
});
});
}
Reference - Calendar API Link
In order to retrieve the meet link from the event, it seems that in the current stage, Calendar API is required to be used. When this is reflected in your script, how about the following modification?
Modified script:
Before you use this script, please enable Calendar API at Advanced Google services.
From:
var NotifyContents = '';
var i = 1;
calendarData.forEach(item => {
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i + ". " + item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n" : "";
NotifyContents += (item.getconferencedata() != "") ? ("\n" + i + ". " + item.getconferencedata()) : ("No Conference\n");
i++;
}
}
)
To:
const eventList = Calendar.Events.list(calendar.getId(), { timeMin: Start.toISOString(), timeMax: End.toISOString(), maxResults: 2500 }).items.reduce((o, e) => (o[e.id] = e.conferenceData.entryPoints.map(({ uri }) => uri).join(","), o), {});
var NotifyContents = '';
var i = 1;
calendarData.forEach(item => {
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i + ". " + item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n" : "";
var eventId = item.getId().split("#")[0];
NotifyContents += eventList[eventId] != "" ? ("\n" + i + ". " + eventList[eventId]) : ("No Conference\n");
i++;
}
});
In this modification, it supposes that calendar has already been declaread. Please be careful about this.
Reference:
Events: list

Regex phone masking

I'm trying to write phone input masking function. Here it is:
let input = document.querySelector('input');
input.addEventListener('input', ()=>{
let x = event.target.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
event.target.value = !x[2] ? x[1] : '+' + x[1] + ' (' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '') + (x[5] ? '-' + x[5] : '');
})
<input />
It works, but with one problem. When I press the backspace key, I erase the phone number to something like +1 (111). Such an entry is valid for the regular expression, and the string is replaced by itself
Per #ggorlen's suggestion in the comments, here is one way to do this:
let input = document.querySelector('input');
input.addEventListener('keydown', (event)=>{
if (event.key === "Backspace" || event.key === "Delete") return;
let x = event.target.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
event.target.value = !x[2] ? x[1] : '+' + x[1] + ' (' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '') + (x[5] ? '-' + x[5] : '');
})
<input maxlength=18 />

Remove "null" from string in javascript

I have this code:
var returnValue = item.fname + " " + item.mname + " " + item.lname
returnValue.replace(null," ");
return returnValue ;
Sometimes one of the fields is null so returnValue is:
"John null Doe"
or
"John something null"
I want to get rid of the "null" but my code does not seem to work.
Can someone help me out here?
Rather than replacing null afterwards, only append the individual names if they are not null.
var returnValue = "";
if (item.fname !== null) {
returnValue += item.fname + " ";
}
if (item.mname !== null) {
returnValue += item.mname + " ";
}
if (item.lname !== null) {
returnValue += item.lname;
}
return returnValue;
Alternatively, use Array.prototype.filter to remove nulls:
// store the names in an array
var names = [ item.fname, item.mname, item.lname ];
// filter the array to values where they are `!== null`
var notNullNames = names.filter(x => x !== null);
// join them with spaces
var returnValue = notNullNames.join(" ");
var returnValue = (item.fname || " ") + " " + (item.mname || " ") + " " + (item.lname || " ");
return returnValue;
Be careful with mixing var types (string and null for example). Better make sure the variable is set or has a fallback.
I'd recommend you another technique: place your string parts to array, filter it and join it:
[item.fname, item.mname, item.lname].filter(v => !!v).join(' ')
try this
> return (item.fname ? item.fname : '') + " " + (item.mname ? item.mname : '') + " " + (item.lname ? item.lname : '');
var returnValue = item.fname
if(item.mname)returnValue += " " + item.mname
if(item.lname)returnValue += " " + item.lname
return returnValue
Try ternary operator for null avoiding:
var returnValue = item.fname + " " + item.mname ? item.mname : "" + " " + item.lname
In my opinion, the most elegant solution is:
[item.fname, item.lname, item.lname].join(' ');
For example:
const item = {}
item.fname = 'foo'
item.lname = 'bar'
console.log([item.fname, item.mname, item.lname].join(' '))
Otherwise you can use the or operator to skip falsy objects:
const item = {}
item.fname = 'foo'
item.lname = 'bar'
const joined = (item.fname || '') + " " + (item.mname || '') + " " + (item.lname || '')
console.log(joined)

Javascript document.getElementByID with condition

I'm reading from a text file some numbers. Sometimes there's a number 0 and the line below outputs 0, but I don't want to output if the number is "0". Is there a way to change the line below to NOT output/print when the number is "0"? Thanks
document.getElementById('inputText').innerHTML= "(" + parseFloat(output1*2).toFixed(3) + "," + parseFloat(output2*2).toFixed(3) + ")";
You can make a function that checks each value and generates a result based on that, like this:
var getResult = function (num1, num2) {
var result1 = num1 ? (parseFloat(num1) * 2).toFixed(3) : "";
result1 = isNaN(result1) ? "" : result1;
var result2 = num2 ? (parseFloat(num2) * 2).toFixed(3) : "";
result2 = isNaN(result2) ? "" : result2;
var comma = result1 && result2 ? ", " : "";
return `(${result1}${comma}${result2})`;
};
document.getElementById('result').innerHTML += `5, 0 = ${getResult("5")}<br/>`;
document.getElementById('result').innerHTML += `0, 4 = ${getResult("0", "4")}<br/>`;
document.getElementById('result').innerHTML += `3, 2 = ${getResult("3", "2")}<br/>`;
document.getElementById('result').innerHTML += `3, 2 = ${getResult("three", "15.5")}<br/>`;
<div id="result"></div>
Edit: Removed possible NaN-results.
You can replace 0 with nothing using the or operator:
parseFloat(output1*2) || ""
or using a ternary:
output1? parseFloat(output1*2).toFixed(3) : ""
document.getElementById('inputText').innerHTML= "(" + ((parseFloat(output1*2).toFixed(3) + ",") ? parseFloat(1*2).toFixed(3):"") + ((parseFloat(output2*2).toFixed(3)) ? parseFloat(1*2).toFixed(3):"") + ")";
Use if statement to check your number:
Html:
<p id="inputText">
0
</p>
Js:
var output = document.getElementById('inputText').innerHTML;
output = parseFloat(output);
if(output != '0'){
inputText.innerHTML= "(" + (output *2)
.toFixed(3) + "," + (output*2).toFixed(3) + ")";
}
https://jsfiddle.net/b5st3h2m/2/

Interesting behavior in my US Number formatting code

I'm trying to make 10 digits look like a US telephone number (i.e.(###) ###-####). My code does accomplish this first goal, but it also does something I can't quite figure out. When typing in the digits, the characters "()" show up before typing any other digits. I want the open parenthesis to appear first and the closing parathesis to appear after entering the third digit. Please don't give me a new solution; try to pin point the issue I'm describing.
<script type="text/javascript">
$('.drumbi-caller-number').live('keydown', function (event) {
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39) {
} else {
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0,3);
var next3 = string.substring(3,6);
var next4 = string.substring(6,9);
var string = ("(" + first3 + ")" + next3 + "-" + next4);
$(this).val(string);
}
});
</script>
Here's a jsFiddle that displays this behavior: http://jsfiddle.net/bigthyme/j6kHn/3/
replace keydown with keyup, on keydown the value of the input element isn't updated
also set your string conditionally, only if long enough:
var string = string.length > 2 ? ("(" + first3 + ")" + next3 + "-" + next4) : first3;
here is the code: http://jsfiddle.net/j6kHn/10
btw: you should also replace .live(...) with .on(...) as .live() is deprecated..
You need to check the length of first3 before appending the paren:
var string = ("(" + first3 + ((first3.length>=3)?")":"") + next3 + "-" + next4);
And although not in your question, you can do the same for the hyphen:
var string = ("(" + first3 +
// only append the ) if the you have 3+ chars
((first3.length>=3)?")":"") +
next3 +
// only append the - if the you have 6+ chars
(((first3+next3).length>=6)?"-":"") +
next4);
You should also use .on() instead of live();
See it all working in this jsFiddle
Go with
$('.foo').on('keyup', function (event) {
$(this).val($(this).val().replace(/\D/g, "").replace(/(\d{0,3})(\d{0,3})(\d{0,4}).*/, "($1) $2-$3"));
});
Test this code here.
Try using this code, it should fix all of your issues:
Demo: http://jsfiddle.net/bN6Rh/3/
jQuery:
$('.foo').on('keyup', function(event) {
if (event.keyCode == (8 || 37 || 39)) { }
else {
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0, 3);
var next3 = " " + string.substring(3, 6);
var next4 = string.substring(6, 10);
if (string.length < 3) { // Less than 3
var string = "(" + first3;
}
else if (string.length > 2 && string.length < 7) { // More than 2 and less than 7
var string = "(" + first3 + ")" + next3;
}
else { // Anything else
var string = "(" + first3 + ")" + next3 + "-" + next4;
}
$(this).val(string);
}
});​
The problem was that you weren't checking the number of characters so as soon as anything was entered it put in ()-, the above code also adds the space you mentioned wanting.
The code could of course be more compressed:
$('.foo').on('keyup', function(e) {
if (e.keyCode == (8 || 37 || 39));
else {
var str = this.value.replace(/[^0-9]/g, "");
var f3 = str.substring(0, 3),
n3 = " " + str.substring(3, 6),
n4 = str.substring(6, 10);
if (str.length<3) str = "(" + f3;
else if (str.length>2&&str.length<7) str="("+f3+")"+n3;
else str="("+f3+")"+n3+"-"+n4;
this.value = str;
}
});​

Categories