JS: how to get resulting value out of its function? - javascript

I process a string, and want to get the end result out of the function so the next function can reuse it. Basically, I currently approach is such:
function pre_processing(str){
str = str.replace(/\d/g, ""); // delete all digit (a simplier example than my code)
return str;
}
function post_processing(){
// do processing n⁰2 on var str
}
pre_processing("w0rd2");
console.log(str) // fails! Uncaught ReferenceError: str is not defined
post_processing(str); // fails, haven't input
This doesn't works. What does I do wrong ? is it a return not done right, or related to asynchroneous JS ? Other ? 2. How to do it right ?
Full JS code there : http://jsfiddle.net/hugolpz/CYwD3/7/ (I made it as simple as possible)

The function then equals that return value, so:
var str = pre_processing("w0rd2");

Your "pre_processing" function returns a string, but you're paying no attention to the return value:
var str = pre_processing("w0rd2");
Now you have a variable called "str" outside the functions.
Of course you can just apply the second function directly to the result of the first:
console.log( post_processing( pre_processing("w0rd2") ) );

You have to assign it to a var when it returns, because the function has now assumes the value of the evaluation, so
var newStr = pre_processing("w0rd2");
Also, shorten your function up with this
return str.replace(/\d/g,"");
instead of str = str.replace(/\d/g,""); return str;
and finally
var newStr = post_processing(newStr);

Related

How can I create a function that creates a unique string from inputs str a and b?

I'm very new to javascript and I was wondering if anyone could help me on this question?
With strings a ="xyaabbbccccdefww" and b="xxxxyyyyabklmopq". I'm supposed to create a function called longest that takes in these two inputs, i.e. function longest(a,b) and return a string that is unique and sorted.
So far my code is:
function longest(s1, s2) {
let val = new Set((s1 + s2));
let newStr = "";
for (let item of val){
newStr += item;
}
let newestStr = function(newStr){
return ((newStr.split('')).sort()).join('');
};
return newestStr;
}
let a = "xyaabbbccccdefww";
let b = "xxxxyyyyabklmopq";
let val1 = longest(a, b);
But this generates function (newStr) { return newStr.split('').sort().join(''); } when I try to print val1. Instead it should return the string abcdefklmopqwxy.
Can someone explain to me where I went wrong? and is there a more efficient way of solving this, cuz the ((newStr.split('')).sort()).join(''); is NlogN which is very long.
Thank you!
You code is correct. But the longest function returns a function instead of the value. Adjust the return statement as:
return newestStr(newStr);

Oracle Apex changing a String of a object

So I want to get the Object which is essentialy a string. The issue is I cant transfer it into the string format since the resulting string is just anything but the thing I want. Bringing the object into a json doesnt bring a proper string either so my only way of achieving that is the concat method.
I have a Popup-Love which returns the string as follows foo, foo1 ,foo2 while I need it as
'foo1','foo2',...,'foo999' .
My method manages to do that for the first element while all the other elements remove the apostrophe resulting in something like 'foo,foo1,foo2'. How do i fix that?
var i = 0;
if(i == 0){
var t ="'";
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
i = i +1;
} else {
var t = t.concat("'");
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
}
You can "overwrite" the native toString() function of the Object and replace it with a function that does what you want. Something like below
function MyObj(){
this.creationTime = new Date().toLocaleString();
}
MyObj.prototype.toString = function something(){
return 'I was created on ' + this.creationTime;
}
var myObj = new MyObj();
console.log('String version of my custom object: ' + myObj);

Mutate string originating from React state

Let's say for some delicate reason I have the following react state:
{ superGreeting: 'Hello!!!' }
Now, assume I have this complicated operation that basically takes the superGreeting string and works on it, in the end replacing a character at a specific position. New state then should be:
{ superGreeting: 'Hullo!!!' }
So, there would be my action:
action = (index) => {
var { superGreeting: newGreeting } = this.state;
newGreeting[index] = 'u';
this.setState({superGreeting: newGreeting});
}
Unfortunatelly, such approach does not work and ends with:
TypeError: Cannot assign to read only property '1' of string 'Hello!!!', indicating this line as the offending one: newGreeting[index] = 'u'
I use react.js, ES6, no redux, no mobx, no immutable.js. Thought that the issue is caused by the string still being related/used by the soon-to-be-previous state, so I thought that creating a copy would work (I tried newGreeting = newGreeting.toString(), '' + newGreeting, `${newGreeting}`, ''.concat(newGreeting), without any success). Any ideas?
Strings in JavaScript are immutable. Your example can be trimmed down to
(function(){
"use strict";
var str = 'Hullo!!!';
str[1] = 'e';
})();
If you want to mutate a string, you'll need to create a new string, e.g.
(function(){
"use strict";
var str = 'Hullo!!!';
str = str.slice(0, 1) + 'e' + str.slice(2);
})();
Strings in JS are immutable, but you can turn it into an array, work on it, then join it back together.. also there are string functions like substr and replace which return a new string if those are applicable.
var split = superGreeting.split('')
split[index] = 'u'
var newGreeting = split.join('')
Your problem here does not have anything to do with react. Strings in javascript are immutable.
You could create the following helper function:
var replaceCharAt = function(str, index, c) {
return str.slice(0, index) + c + str.slice(index+1)
}
so that
replaceCharAt('012', 1, 'x') === '0x2'

JavaScript get url segment and parameter

I've read some question but I still can't figure out how to do it
I have a url example.com/event/14aD9Uxp?p=10
Here I want to get the 14aD9Uxp and the value of p
I've tried using split('/'+'?p=') but it doesn't work
I want to use regex but I dont really understand how to use it
var URL='example.com/event/14aD9Uxp?p=10';
var arr=URL.split('/');//arr[0]='example.com'
//arr[1]='event'
//arr[2]='14aD9Uxp?p=10'
var parameter=arr[arr.length-1].split('?');//parameter[0]='14aD9Uxp'
//parameter[1]='p=10'
var p_value=parameter[1].split('=')[1];//p_value='10';
I've created a generalized function (restricted in some ways) that will return the GET value given the parameter. However this function will only work correctly provided that you do not Rewrite the URL or modify the URL GET SYNTAX.
//Suppose this is your URL "example.com/event/14aD9Uxp?p=10";
function GET(variable) {
var str = window.location.href;
str = str.split("/");
// str = [example.com, event, 14aD9Uxp?p=10]
//Get last item from array because this is usually where the GET parameter is located, then split with "?"
str = str[str.length - 1].split("?");
// str[str.length - 1] = "14aD9Uxp?p=10"
// str[str.length - 1].split("?") = [14aD9Uxp, p=10]
// If there is more than 1 GET parameter, they usually connected with Ampersand symbol (&). Assuming there is more, we need to split this into another array
str = str[1].split("&");
// Suppose this is your URL: example.com/event/14aD9Uxp?p=10&q=112&r=119
// str = [p=10, q=112, r=119]
// If there is only 1 GET parameter, this split() function will not "split" anything
//Remember, there might only be 1 GET Parameter, so lets check length of the array to be sure.
if (str.length > 1) {
// This is the case where there is more than 1 parameter, so we loop over the array and filter out the variable requested
for (var i = 0; i < str.length; i++) {
// For each "p=10" etc. split the equal sign
var param_full_str = str[i].split("=");
// param_full_str = [p, 10]
//Check if the first item in the array (your GET parameter) is equal to the parameter requested
if (param_full_str[0] == variable) {
// If it is equal, return the second item in the array, your GET parameter VALUE
return param_full_str[1];
}
}
} else {
// This is the case where there is ONLY 1 GET parameter. First convert it to a String Type because Javascript decided that str was no longer a String
// Now split it with the equal sign.
str = str.toString().split("=");
return str[1];
}
}
document.write(GET("p"));
function $_GET(param) {
var vars = {};
window.location.href.replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
I have collected this from here:
http://www.creativejuiz.fr/blog/javascript/recuperer-parametres-get-url-javascript
It works great.
To use it just grab your parameter like:
var id = $_GET('id');
const url = new URL('http://example.com/event/14aD9Uxp?p=10');
const [,, eventId ] = url.pathname.split('/');
const p = url.searchParams.get('p');
Browser support:
https://caniuse.com/#feat=url
https://caniuse.com/#feat=urlsearchparams
Simple no-regex way
var s = "example.com/event/14aD9Uxp?p=10";
var splitByForwardSlash = s.split('/');
// To get 14aD9Uxp
splitByForwardSlash[splitByForwardSlash.length-1]
// To get p=10
splitByForwardSlash[splitByForwardSlash.length-1].split('?')[1]
I think you know how to go from here :-)

Replacing a substring of an element's text with another string

The Problem
I'm trying to use the JavaScript string replace method to replace some text in a div if it contains a certain string. However, my code does not replace the string inside that div.
The Javascript
function john(){
var NAME = "Johnny Buffet,";
var val = $("div#like-list-").text();
if ( val.indexOf(NAME) !== -1 ){
val.replace(NAME, '');
}
}
It doesn't work because .replace() is a String function and not a jQuery function; Strings in JavaScript are immutable, so .replac() returns the modified String which you then have to reassign to your element.
That said, you can use .text(fn) to perform the replacement in a single step:
$("div#like-list-").text(function(i, val) {
return val.replace(NAME, '');
});
Btw, I've removed the .indexOf() condition as well, because if NAME doesn't occur inside your string, the .replace() function will just return the original string.
You're editing the string, then simply throwing it away. Take the edited val and put it's contents back into the HTML element using a parameterized call to the text method.
function john(){
var NAME = "Johnny Buffet,";
var val = $("div#like-list-").text();
if ( val.indexOf(NAME) !== -1 ){
$("div#like-list-").text(val.replace(NAME, ''));
}
}
replace() is javascript not jQuery and you need to reset the value to variable after replace as replace() returns the updated text;
ie;
val = val.replace(NAME, '');
so try:
function john(){
var NAME = "Johnny Buffet,";
var val = $("div#like-list-").text();
if ( val.indexOf(NAME) !== -1 ){
val = val.replace(NAME, '');
}
}

Categories