JQuery / Javascript & Split within split? - javascript

A Caveat: As a dilettante I lack the vocabulary to precisely describe my problem. Bear with me.
Let's assume I have a string like the following one:
A1%%A2%%A3%%A4||B1%%B2%%B3%%B4||C1%%C2%%C3%%C4||D1%%D2%%D3%%D4
Using JavaScript / JQuery I would like to split it twice (using '||' and '%%' as delimiters) and have the following HTML as output:
<p><input value="A1"></input><input value="A2"></input><input value="A3"></input><input value="A4"></input></p>
<p><input value="B1"></input><input value="B2"></input><input value="B3"></input><input value="B4"></input></p>
<p><input value="C1"></input><input value="C2"></input><input value="C3"></input><input value="C4"></input></p>
<p><input value="D1"></input><input value="D2"></input><input value="D3"></input><input value="D4"></input></p>
I know how to do basic splitting and joining, but this goes beyond my comprehension.

You can use something like this.
s = "A1%%A2%%A3%%A4||B1%%B2%%B3%%B4||C1%%C2%%C3%%C4||D1%%D2%%D3%%D4";
s2 = s.split("||");
s2.forEach(function(item){
s3 = item.split("%%");
s3.forEach(function(item2){
console.log(item2);
});
});

You can use replace
function splitString(match, part) {
switch (part) {
case '%%':
return '"></input><input value="';
case '||':
return '"></input></p>\n<p><input value="';
}
}
var formattedValue = 'A1%%A2%%A3%%A4||B1%%B2%%B3%%B4||C1%%C2%%C3%%C4||D1%%D2%%D3%%D4'.replace(/(%%|\|\|)/g, splitString);
formattedValue = '<p><input value="' + formattedValue + '"></input></p>';
console.log(formattedValue);

All split joins. It will be fast.
var str = 'A1%%A2%%A3%%A4||B1%%B2%%B3%%B4||C1%%C2%%C3%%C4||D1%%D2%%D3%%D4',
result = str.split('||').join('"></input></p>\n<p><input value="');
result = '<p><input value="'+
result.split('%%').join('"></input><input value="')+
'"></input></p>';
console.log(result);
//or
//alert(result);
//
With problems like this don't think so much about what format you want.
Start with something simple first like:
var result = str.split('||').join('><');
result = str.split('%%').join('><');
Then you might see how to use the longer string to get what you actually want.

Related

I'm trying to use parseint but it does not work

I'm writing a script and I want a H1 tag to increase with an input's value. But it doesn't work. I'm probably dumb, but I'm here cause I want help.
This is my code:
var h1Value = 0;
function addFun() {
var changeH1By = document.getElementById('input').value;
parseInt('h1Value') + parseInt('changeH1By');
document.getElementById('h1').innerHTML = h1Value;
}
<h1 id="h1">0</h1>
<input type="number" id="input" value="1">
<button onclick="addFun()">Add</button>
As you probably see I'm using parseInt(), because else the h1 was "11". Like 1 + 1 = 11? Am I using the parseInt wrong or is something else wrong?
Thank you!
You were passing an string into parseInt, remove the quotes to pass the variable.
You didn't assign the result of parseInt('h1Value') + parseInt('changeH1By');to any variable
Instead off keeping track of var h1Value, lets use document.getElementById('h1').innerHTML to get the current value
Removed newValue so we can set the new value instant as innerHTML
function addFun() {
var currentvalue = document.getElementById('h1').innerHTML;
var changeH1By = document.getElementById('input').value;
document.getElementById('h1').innerHTML = parseInt(currentvalue) + parseInt(changeH1By);
}
<h1 id="h1">0</h1>
<input type="number" id="input" value="1">
<button onclick="addFun()">Add</button>
You're passing the strings "h1Value" and "changeH1By" to parseInt and it's trying to parse those literal strings to integers. If you try logging the result of e.g. parseInt("h1Value") it evaluates to NaN, i.e. "not a number", which would give you a hint of where you're going wrong.
A working version of your code would be
var h1Value = 0;
function addFun() {
var changeH1By = document.getElementById('input').value;
h1Value = h1Value + parseInt(changeH1By);
document.getElementById('h1').innerHTML = h1Value;
}
The type of h1Value is already a number, so it doesn't need to be coerced into one, and instead of calling parseInt with the literal string "changeH1By", you'll need to give the actual variable as an argument. Also the line
parseInt('h1Value') + parseInt('changeH1By');
doesn't do anything by itself, the javascript engine will just compute the value and throw it away, as you're not saving it into a variable etc.
A clean way for coding that...
<input..> elements of type="number" have a valueAsNumber property
use const to avoid repeating the results of these interpretations
const
h1_element = document.getElementById('h1')
, changeH1By = document.getElementById('input')
;
function addFun()
{
h1_element.textContent = changeH1By.valueAsNumber
+ parseInt(h1_element.textContent)
}
<h1 id="h1">0</h1>
<input type="number" id="input" value="1">
<button onclick="addFun()">Add</button>

Parsing a string into JS language as well as parsing string into json or xml

Update on 16 Jan 2021
I have looked at this question later, finding that it is a silly question, as we can evaluate js code using eval, or by constructing a function
new Function(...paramsAsString, codeAsString)
BTW, here is a bud-version of the app I was working on.
I want to create a simple graphing calculator, the user will put the
mathematical expression into an input element, js will reach it using input.value :
let input = document.querySelector('#text');
while drawing the function I can use eval(...); but it is so slow,
so I will be so grateful if you have any way to store some string looks like this
("x => " + "sin(x)") into a variable that is a function,
let expr = parseJS("x => " + "sin(x)");
console.log(expr(PI));
// 1
would something like this be what you are looking for?
let expr = x => Math.sin(x);
function btnSubmit(){
let input = parseFloat(document.querySelector('#text').value);
alert( expr(input) );
}
Enter a number: <input id="text" type="number" step="any">
<input type="submit" onclick="btnSubmit()">
Hopefully, I have solved this problem and I want to share knowledge with you.
this is the code to get a variable as a JS function:
var fucnsExprScript1 = document.createElement('script');
fucnsExprScript1.appendChild(document.createTextNode(`let funcExpr = [(x => NaN)]`));
document.body.appendChild(fucnsExprScript1);
function generateJSfunction(text){
let func = `funcExpr.push(x => ${text});`;
let fucnsExprScript2 = document.createElement('script');
fucnsExprScript2.textContent = func;
document.body.appendChild(fucnsExprScript2);
fucnsExprScript2.remove();
return funcExpr[funcExpr.length - 1];
}
By this you can convert any string you want into any supported programming lang you want while the web is live.
You can also put a tea-area element and let users to type js code to handle by clicking a button.
This is after reflecting deep.
Edition
the hereabove code is quite stupid, when I typed it I had not enough knowledge about the native function "eval", so the answer is:
function getJSfuntion(str){
return eval("x => " + str);
// or
// return Function("x", `return {str};`);
}

Manipulate text from form - JavaScript/Jquery

Hello I am working on a project and last night I had a thought that would make a lot of what I am wanting to do a heck of a lot easier, the only problem is I am not sure on the best way to tackle it. Let me explain....
I have a form on a website where a user enters a VIP ID that is in a pre-determined format and follows a logical naming convention.
Example: app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb
I want to pull out the following information from the entered text.
prod.platform.org.
Then I want to reverse it logically
.org.platform.prod
And then I want to replace the “.” For “/”
/org/platform/prod
And finally I want to add a postfix of “/open*”
/org/platform/prod/open*
So in short,
INPUT = app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb
OUTPUT = /org/platform/prod/open*
I am using javascript/jquery for everything else but I am pretty new to all of this so I tend not to know the best route to tackle a problem. If I need to provide some more detail I can do. Any help is much appreciated.
Or simple like this
var input = "app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb" ;
var output =
"/" +
input
.split(".")
.slice(1, 4)
.reverse()
.join("/") +
"/open";
var output =
"/" +
"app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb"
.split(".")
.slice(1, 4)
.reverse()
.join("/") +
"/open";
You can try below code :
var input = "app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb";
var tempArr = input.split(".");
var newArr = new Array();
for(var i=1;i<tempArr.length;i++){
if(tempArr[i]=="org" || tempArr[i]=="net"){
newArr.push(tempArr[i]);
break;
}
newArr.push(tempArr[i]);
}
newArr.reverse();
var output="/"+newArr.join("/")+"/open*";

Convert unicode from Json in HTML with Javascript

I am getting issues to convert unicode and render in a nice HTML code.
Here is the information i have as an input in my Json file
`"CLIENT:\r\n-Client1: Project1\u00c2\u00a0\r\n- Client2: etc..."`
I would like this to render as below in
CLIENT:
- client1: Project 1
- Client2: etc...
It currently renders like this :
`CLIENT: - Client1: Project1Â - Client2: etc...`
I looked everywhere but could not find a function that could handle all unicodes to decode in nice html code.
Thanks in advance!
Maybe you can take a look at this:
How do I replace all line breaks in a string with tags?
You do this:
str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');
before insert into the html.
If you are using javascript, you can use this fragment
<script>
var c = decodeURIComponent(escape(`"CLIENT:\r\n-Client1: Project1\u00c2\u00a0\r\n- Client2: etc..."`));
c = c.replace(/(?:\r\n|\r|\n)/g, '');
c = c.replace(':-', ': - ');
document.write(c);
</script>
Ok I managed to make this work with the below function:
function strFormat(str) {
var c= decodeURIComponent(escape(str));
c= c.replace(/(?:\r\n|\r|\n)/g, '<br />');
c= c.replace(':-', ': - ');
return c;
}
Let me know if there are any cleaner way to do this?

Node.innerHTML giving tag names in lower case

I am iterating NodeList to get Node data, but while using Node.innerHTML i am getting the tag names in lowercase.
Actual Tags
<Panel><Label>test</Label></Panel>
giving as
<panel><label>test</label></panel>
I need these tags as it is. Is it possible to get it with regular expression? I am using it with dojo (is there any way in dojo?).
var xhrArgs = {
url: "./user/"+Runtime.userName+"/ws/workspace/"+Workbench.getProject()+"/lib/custom/"+(first.type).replace(".","/")+".html",
content: {},
sync:true,
load: function(data){
var test = domConstruct.toDom(data);
dojo.forEach(dojo.query("[id]",test),function(node){
domAttr.remove(node,"id");
});
var childEle = "";
dojo.forEach(test.childNodes,function(node){
if(node.innerHTML){
childEle+=node.innerHTML;
}
});
command.add(new ModifyCommand(newWidget,{},childEle,context));
}
};
You cannot count on .innerHTML preserving the exact nature of your original HTML. In fact, in some browsers, it's significantly different (though generates the same results) with different quotation, case, order of attributes, etc...
It is much better to not rely on the preservation of case and adjust your javascript to deal with uncertain case.
It is certainly possible to use a regular expression to do a case insensitive search (the "i" flag designates its searches as case insensitive), though it is generally much, much better to use direct DOM access/searching rather than innerHTML searching. You'd have to tell us more about what exactly you're trying to do before we could offer some code.
It would take me a bit to figure that out with a regex, but you can use this:
var str = '<panel><label>test</label></panel>';
chars = str.split("");
for (var i = 0; i < chars.length; i++) {
if (chars[i] === '<' || chars[i] === '/') {
chars[i + 1] = chars[i + 1].toUpperCase();
}
}
str = chars.join("");
jsFiddle
I hope it helps.
If you are trying to just capitalise the first character of the tag name, you can use:
var s = 'panel';
s.replace(/(^.)(.*)/,function(m, a, b){return a.toUpperCase() + b.toLowerCase()}); // Panel
Alternatively you can use string manipulation (probably more efficient than a regular expression):
s.charAt(0).toUpperCase() + s.substring(1).toLowerCase(); // Panel
The above will output any input string with the first character in upper case and everything else lower case.
this is not thoroughly tested , and is highly inefficcient, but it worked quite quickly in the console:
(also, it's jquery, but it can be converted to pure javascript/DOM easily)
in jsFiddle
function tagString (element) {
return $(element).
clone().
contents().
remove().
end()[0].
outerHTML.
replace(/(^<\s*\w)|(<\/\s*\w(?=\w*\s*>$))/g,
function (a) {
return a.
toUpperCase();
}).
split(/(?=<\/\s*\w*\s*>$)/);
}
function capContents (element) {
return $(element).
contents().
map(function () {
return this.nodeType === 3 ? $(this).text() : capitalizeHTML(this);
})
}
function capitalizeHTML (selector) {
var e = $(selector).first();
var wrap = tagString(e);
return wrap[0] + capContents(e).toArray().join("") + wrap[1];
}
capitalizeHTML('body');
also, besides being a nice exercise (in my opinion), do you really need to do this?

Categories