Manipulate replace string in javascript - javascript

I have three variables in javascript like
var a = document.getElementById("txtOrderNumberRelease1").value;
var b = document.getElementById("txtOrderNumberRelease2").value
var c = document.getElementById("ddlOrderNumberRelease3");
and
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY"
In mainString, the value "789" is coming from variable "a",
value "456" is coming from variable b and value "LLX" is coming from variable "c".
Variables "a" and "b" will always be Integers, whereas variable "c" will always be one the three values ie. "LLI,LLA,LLX".
Before value "789", there can be any number of words splitted by hypen "-". like ROAM-LCD-Synergy-SSI etc...
But after the value of variable "c" i.e "LLX" in mainString, there can be only one word for eg. "WARRANTY".
Now my issue is, I have to replace these three values of "a","b" and "c" ie. "789-456-LLX" with my newly entered values lets say 987-654-LLA, then my desired final string would be
old string: mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY"
desired string: mainString ="ROAM-LCD-Synergy-987-654-LLA WARRANTY"
Please suggest some wayout.
Thanks

var a = 123;
var b = 456;
var c = "ABC";
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY";
var updatedString = mainString .replace(/\d{3}-\d{3}-[A-Z]{3}\s([^\s]*)$/,a+"-"+b+"-"+c+" $1");
console.log(updatedString);

Something like this should work:
mainString.replace(/[\d]{3}\-[\d]{3}\-[\w]{3}\s([\w]+)$/, a + "-" + b + "-" + c + " $1");

Here's an option that uses string.split.
function replaceLastThreeDashedFields(original,a,b,c) {
var spaceSplit = original.split(' ');
var dashSplit = spaceSplit[0].split('-');
dashSplit[dashSplit.length - 3] = a;
dashSplit[dashSplit.length - 2] = b;
dashSplit[dashSplit.length - 1] = c;
var newDashed = dashSplit.join('-');
spaceSplit[0] = newDashed;
var newSpaced = spaceSplit.join(' ');
return newSpaced;
}

Just change the values before they are assigned? Place this before your variables are declared.
document.getElementById("txtOrderNumberRelease1").value = '987';
document.getElementById("txtOrderNumberRelease2").value = '654';
document.getElementById("txtOrderNumberRelease3").value = 'LLA';

The following code should update based on the values of a, b, and c...
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY";
var a = document.getElementById("txtOrderNumberRelease1").value;
var b = document.getElementById("txtOrderNumberRelease2").value;
var c = document.getElementById("ddlOrderNumberRelease3");
mainString = mainString.replace("789",a);
mainString = mainString.replace("456",b);
mainString = mainString.replace("LLX",c);

Related

Javascript sliptstring into 2 variables

I could not find any usefull post here about my little question.
I have a variable that contains a string and I want it splited into 2 variables.
Example:
var str = "String1;String2";
I want:
var str = "String1;String2";
var string1 = "String1";
var string2 = "String2";
var string1 = str.split(";")[0];
var string2 = str.split(";")[1];
More about split method: Split String Method
You can use the window object for assigning global variables.
var str = "String1;String2";
str.split(';').forEach(function (a) {
window[a] = a;
});
document.write(String1 + ' ' + String2);

How to split math calculations in javascript

I have mathematical calculations in div tag, like that:
13*7=91
So how to split and parse data?
and it will stored in variables like that:
var A = 13;
var Operation = '*';
var B = 7;
var Result = 91;
please tell me how to make that :)
You can split it first by = sign, and then by possible math signs, for example:
var s = '13*7=91';
var a = s.split('=');
var b = a[0].split(/[\+\-\*\/\^%]/);
var A = b[0];
var B = b[1];
var Operation = a[0].replace(A,'').replace(B,'');
var Result = a[1];
console.log(A+Operation+B+'='+Result);
Output:
13*7=91
This is an easy way of doing it, simply using RegExp.
The first one is /[0-9]+/g to take the operands and the result numbers and the second one is /[0-9]+(.)[0-9]+/ to extract the operator, then I print the result in a diplay p elemnt:
var str = document.getElementById("calcul").innerText;
var re = /[0-9]+/g;
var re2 = /[0-9]+(.)[0-9]+/;
var operands = str.match(re);
var operator = str.match(re2)[1];
var A = operands[0];
var B = operands[1];
var result = operands[2];
var display = document.getElementById("display");
display.innerHTML = "var A = " + operands[0] + "<br>var B = " + operands[1] + "<br>var result = A" + operator + "B =" + result;
<div id="calcul">
13*7=91
</div>
<br>Calculation results :
<p id="display">
</p>
Maybe you can try something like this:
Make a regular expression that detects the numbers separated by anything (+, *, -, /, =, etc).
Make that regular expression detects the separating elements.
Then execute eval() in javascript. Be careful with this.
When you have a piece of code show us and we can help you better.
Good luck.

Need to strip a leading character (# or +) from this string

In the cases below I need to strip either the first "#" or "+" character for vars b & c so they can become vars a & a1 which are used to be a string in a new url that's built elsewhere.
Here is the code:
var b = "http://www.somewhere.com/search/#foo+bar+baz"
var c = "http://www.somewhere.com/search/++bar+baz"
var a = b.split("/")[4].split("+").slice(0, 1);
var a1 = c.split("/")[4].split("+").slice(0, 1);
Here is the fiddle.
This works for me on your fiddle.
var b = "http://www.somewhere.com/search/#foo+bar+baz"
var c = "http://www.somewhere.com/search/++bar+baz"
var a = b.split("/")[4].split("+").slice(0, 1);
if(a[0].indexOf('#') != -1){a = a[0].split('#')[1]}
var a1 = c.split("/")[4].split("+");
var i=0;
while(true){
if(a1[i] != ''){a1 = a1[i]; break;}
i++;
}
$("#result").html(a);
$("#result2").html(a1);
console.log(a);
console.log(a1);
Updated your fiddle
You can replace the first occurrence of a char with using a regex quite easily:
var a = b.replace(/[#+]/,'');
var a1 = c.replace(/[#+]/,'');
Without the g modifier it will only replace the first one it finds.

Javascript How to define multiple variables on a single line?

Reading documentation online, I'm getting confused how to properly define multiple JavaScript variables on a single line.
If I want to condense the following code, what's the proper JavaScript "strict" way to define multiple javascript variables on a single line?
var a = 0;
var b = 0;
Is it:
var a = b = 0;
or
var a = var b = 0;
etc...
Using Javascript's es6 or node, you can do the following:
var [a,b,c,d] = [0,1,2,3]
And if you want to easily print multiple variables in a single line, just do this:
console.log(a, b, c, d)
0 1 2 3
This is similar to #alex gray 's answer here, but this example is in Javascript instead of CoffeeScript.
Note that this uses Javascript's array destructuring assignment
You want to rely on commas because if you rely on the multiple assignment construct, you'll shoot yourself in the foot at one point or another.
An example would be:
>>> var a = b = c = [];
>>> c.push(1)
[1]
>>> a
[1]
They all refer to the same object in memory, they are not "unique" since anytime you make a reference to an object ( array, object literal, function ) it's passed by reference and not value. So if you change just one of those variables, and wanted them to act individually you will not get what you want because they are not individual objects.
There is also a downside in multiple assignment, in that the secondary variables become globals, and you don't want to leak into the global namespace.
(function() { var a = global = 5 })();
alert(window.global) // 5
It's best to just use commas and preferably with lots of whitespace so it's readable:
var a = 5
, b = 2
, c = 3
, d = {}
, e = [];
There is no way to do it in one line with assignment as value.
var a = b = 0;
makes b global. A correct way (without leaking variables) is the slightly longer:
var a = 0, b = a;
which is useful in the case:
var a = <someLargeExpressionHere>, b = a, c = a, d = a;
Why not doing it in two lines?
var a, b, c, d; // All in the same scope
a = b = c = d = 1; // Set value to all.
The reason why, is to preserve the local scope on variable declarations, as this:
var a = b = c = d = 1;
will lead to the implicit declarations of b, c and d on the window scope.
Here is the new ES6 method of declaration multiple variables in one line:
const person = { name: 'Prince', age: 22, id: 1 };
let {name, age, id} = person;
console.log(name);
console.log(age);
console.log(id);
* Your variable name and object index need be same
Specifically to what the OP has asked, if you want to initialize N variables with the same value (e.g. 0), you can use array destructuring and Array.fill to assign to the variables an array of N 0s:
let [a, b, c, d] = Array(4).fill(0);
console.log(a, b, c, d);
note you can only do this with Numbers and Strings
you could do...
var a, b, c; a = b = c = 0; //but why?
c++;
// c = 1, b = 0, a = 0;
do this if they have same value
let x = y = z = 0
otherwise
let [x, y, z] = [10, 30, 50]
console.log(x, y, z) // 10 30 50
The compressed type of that is here:
var a, b = a = "Hi";
& for 3 variables:
var x, y, z = x = y = "Hello";
Hope to be helpful!
This is completely correct:
var str1 = str2 = str3 = "value";
And if change one of their value, the value of other variables won't change:
var str1 = str2 = str3 = "value";
/* Changing value of str2 */
str2 = "Hi Web!";
document.write("str1 = " + str1 + " - str2 = " + str2 + " - str3 = " + str3);

Merging the Strings

HI ,
In Java Script ,
var a ="apple-orange-mango"
var b ="grapes-cheery-apple"
var c = a + b // Merging with 2 variable
var c should have value is "apple-orange-mango-grapes-cheery" .Duplicated should be removed.
Thanks ,
Chells
After your string is combined, you will want to split it using the delimiters (you can add these back in later).
example:
var a ="apple-orange-mango"
var b ="grapes-cheery-apple"
var c = a + "-" + b
var Splitted = c.split("-");
the Splitted variable now contains an array such as [apples,orange,mango,grapes,cherry,apple]
you can then use one of many duplicate removing algorithms to remove the duplicates. Then you can simply do this to add your delimiters back in:
result = Splitted.join("-");
Here's a brute force algorithm:
var a;
var b; // inputs
var words = split(a+b);
var map = {};
var output;
for( index in words ) {
if( map[ words[index] ]!=undefined ) continue;
map[ words[index] ] = true;
output += (words[index] + '-');
}
output[output.length-1]=' '; // remove the last '-'
The map acts as a hashtable.
Thats it!
I don't know if it is an homework.
By the way you can split strings like a and b with the split method of string object.
in your case:
firstArray=a.split("-");
secondArray=b.split("-");
the removal of duplicates is up to you...
In your simple example, just use var c = a + "-" + b;
If you want duplicates removed, split a and b into arrays, and combine them, like so:
var avalues = a.split("-");
var bvalues = b.split("-");
var combined = avalues.concat( bvalues );
// now loop over combined and remove duplicates

Categories