JS: How to make multiline strings appear on one line? - javascript

I have a string in my JS code that I want to include three parts, each rendered conditionally.
let a = `
${condition1 ? <text1> : ""}
${condition2 ? <text2> : ""}
${condition3 ? <text3> : ""}
`
I want a to be all on one line, but this renders on multiple lines. The reason I wrote the code on multiple lines is for ease of reading.
Is there a way to write the code on multiple lines but have the string render on one?

Avoid template string literals
let a = (condition1 ? <text1> : "")
+ (condition2 ? <text2> : "")
+ (condition3 ? <text3> : "");
Example:
let a = (true ? "text1" : "")
+ (false ? "text2" : "")
+ (true ? "text3" : "");
console.log(a);

You could simply add backslashes (\) after each line.
const condition1 = true,
condition2 = true,
condition3 = true;
let a = `\
${condition1 ? 'text1' : ""} \
${condition2 ? 'text2' : ""} \
${condition3 ? 'text3' : ""}
`;
console.log(a)
Hint: Ensure that you remove spaces.

Related

How to create a dynamic regex based on condition?

I'm trying to create a password generator where I can tick options (letters / numbers / special characters)...
For each ticked input, I want to generate a different regex pattern that accept wider range of characters, with at least white spaces accepted :
const alpha = alphaInputEl.checked;
const numeric = numericInputEl.checked;
const special = specialInputEl.checked;
return new RegExp(`/[
${alpha ? "a-zA-Z " : " "}
${numeric ? "0-9" : ""}
${special ? "$&+,:;=?##|'<>.^*()%!-" : ""}
]/`)
But I can't test against that regex. How can I build that regex dynamically ?
Answering my own question. I removed the slashes to make it work.
Doc ref: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Working version:
return new RegExp(`[${alpha ? "a-z-A-Z " : " "}${numeric ? "0-9" : ""}${special ? "$&+,:;=?##|'<>.^*()%!-" : ""}]`)

How to split() string with double square brackets in Javascript

I want to change this
let str = "Tom left from [[his]] home";
to
array = ["Tom left from ", "[[his]]", " home"];
I have tried like this
array = []; c = 0;
array = str.split(/([[[]]])/).filter(Boolean).forEach(e =>
e == '[[' ? c++ : e == ']]' ? c-- : c > 0 ? array.push('[[' + e + ']]') : array.push(e)
);
console.log(array)
try this
str.split(/(\[\[.+?\]\])/).filter(Boolean)
and thats it, no need some extra execution
PS About your code:
1) Square brackets inside regular expression needs backslashes in front of them since they are parts of expressions syntax
2) forEach just iterates over elements, it returns undefined, so your code is totally meaningless when you assign value to array, so whatever you made with variable array, you annigilated, in such case use map function, which creates a new array, transforming vaues of existing
array = str.split(/whatever/).filter(Boolean).map(e =>
e == '[[' ? c++ : e == ']]' ? c-- : c > 0 ? '[[' + e + ']]' : e
);

replace '.' with '' in ternary operator

I want to check the string starts with '.' eg .net and replace it as net using ternary operator in javascript.I want to replace the below code with ternary operator
arr = ".net"
var val = arr.startsWith('.');
if(val == true)
{
arr = arr.replace('.','');
}
else
{
arr;
}
tried as
arr = arr.startsWith('.') ? arr.replace('.','') : arr;
var arr = '.net'
arr = arr.startsWith('.')
? arr.slice(1)
: arr
You probably don't want to replace the . as there could be a . elsewhere in the string. .slice will just remove the first character and return the rest.
You can use regex for that.
Idea:
Create a pattern which checks for string that starts with .
Use it to replace to blank string.
If a string does not start with ., it will not replace.
function replace(str) {
return str.replace(/^\./, '')
}
console.log(replace('.net'))
console.log(replace('asp.net'))
function removeDot(arr) {
return arr.startsWith('.') ? arr.slice(1) : arr;
}
You can add a function like removeDot, invoke it with whatever string you want and get the output without dot.

Appending to a Javascript String using ?: in the expression behaves unexpectedly

var aString = "test ";
aString = aString + true?"Appended":"No Append"; // 'Appended'
where as
aString = aString + (true?"Appended":"No Append");// 'test Appended'
What exactly is happening?
The first case adds true to aString and then checks with the ternary.
It is basically this operation with parenthesis
(aString + true) ? "Appended" : "No Append"
The overall answer is the operator precedence of + over ?.
var aString = "test ";
console.log(aString + true ? "Appended" : "No Append"); // 'Appended'
console.log((aString + true) ? "Appended" : "No Append"); // 'Appended'
console.log(aString + (true ? "Appended" : "No Append")); // 'test Appended'
The reason is that javascript Operator precedence(look)
I think in this case aString + true is evaluated before the rest of the expression.
So you get
if(aString + true) {
aString = "Appended";
}
which you fixed with brackets, turning it into
if(true) {
aString = aString + "Appended";
}

Replace first character of string

I have a string |0|0|0|0
but it needs to be 0|0|0|0
How do I replace the first character ('|') with (''). eg replace('|','')
(with JavaScript)
You can do exactly what you have :)
var string = "|0|0|0|0";
var newString = string.replace('|','');
alert(newString); // 0|0|0|0
You can see it working here, .replace() in javascript only replaces the first occurrence by default (without /g), so this works to your advantage :)
If you need to check if the first character is a pipe:
var string = "|0|0|0|0";
var newString = string.indexOf('|') == 0 ? string.substring(1) : string;
alert(newString); // 0|0|0|0​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
You can see the result here
str.replace(/^\|/, "");
This will remove the first character if it's a |.
var newstring = oldstring.substring(1);
If you're not sure what the first character will be ( 0 or | ) then the following makes sense:
// CASE 1:
var str = '|0|0|0';
str.indexOf( '|' ) == 0 ? str = str.replace( '|', '' ) : str;
// str == '0|0|0'
// CASE 2:
var str = '0|0|0';
str.indexOf( '|' ) == 0? str = str.replace( '|', '' ) : str;
// str == '0|0|0'
Without the conditional check, str.replace will still remove the first occurrence of '|' even if it is not the first character in the string. This will give you undesired results in the case of CASE 2 ( str will be '00|0' ).
Try this:
var str = "|0|0|0|0";
str.replace(str.charAt(0), "");
Avoid using substr() as it's considered deprecated.
It literally is what you suggested.
"|0|0|0".replace('|', '')
returns "0|0|0"
"|0|0|0|0".split("").reverse().join("") //can also reverse the string => 0|0|0|0|

Categories