Arrangement of two string charecters into one string using loop - javascript

I have two string which should be put together into one string. First string is a input value and second string is a pattern how the first string should look. Here is the example - Input string( var val ) - 9165678823 Patter string( var mask ) - (999)999-9999 Output string should look like( var startVal ) - (916)567-8823 I have tried working out and this is my code
var val = $(control).data("loadMaskValue"); // Input Value
var mask = $(control).attr("mask"); //Masking Pattern
var startVal = "";
var j = 0;
for (var i = 0; i < mask.length; i++) {
var c = mask.charAt(j);
if (c == '9' || c == 'X' || c == 'A') { //Checks the char is normal char
startVal += val.charAt(j);
}
else {
startVal += c; //Inserts the special char to string like ( ) -
startVal += val.charAt(j);
}
j = startVal.length;
}
The problem with this code is it misses one number in between. The result of this code is startValue - (965)688-2. PLease help me.

Here's a slightly simpler implementation:
var input = '9165678823';
var mask = '(999)999-9999';
var output = '';
var offset = 0;
for (var i = 0; i < mask.length; i++) {
var char = mask.charAt(i);
if ('9XA'.indexOf(char) != -1) {
output += input.charAt(i - offset);
} else {
output += mask.charAt(i);
offset += 1;
}
}
console.log(output);
​Make sure that input has been stripped of all whitespace at the beginning and end.
Demo: http://jsfiddle.net/qWtjk/

You can use a regular expression to take the elements out. Check the fiddle: http://jsfiddle.net/BuddhiP/9MmqS/
var str= '9165678823';
var regEx = new RegExp("(\d{3})(\d{3})(\d{4})");
var m = regEx.exec(str);
var res = '(' + m[1] + ')' + m[2] + '-' + m[3];
console.log(res);
result is (916)567-8823
UPDATE: How to make this work with a dynamic pattern. Check updated fiddle: http://jsfiddle.net/BuddhiP/9MmqS/
$(function() {
var str= '9165678823';
var regEx = new RegExp("(\\d{3})(\\d{3})(\\d{4})");
var m = regEx.exec(str);
var mask = "({0}){1}-{2}";
var res = mask.supplant(m.slice(1));
console.log(res);
});​
Using supplant method from here: http://javascript.crockford.com/remedial.html
Once you understand your regular expression, you can make this work with any pattern and mask.

Related

Reverse String In Place Using for loop in JavaScript

var n = "reversestrings", k=3;
want to reverse string in chunk of 'k',
Answer would be : ver sre tse nir gs;
if Last word less then 'k' then don't need to reverse.
I am using below code but not getting expected answer.
var n = 'stringreverses', k = 3, str = '', s = '';
var c = 0;
for( var i=0; i<n.length; i++ ){
if( c<k ){
c++
str += n[i];
s=str.split('').reverse().join('');
}
else{
console.log("-" + s);
c=0;
}
}
First we need to split input to chunks with the same size (the last one can be smaller), next we reverse every chunk and concatenate at the end.
var input = "123456",
chunks = input.match(new RegExp('.{1,' + k + '}', 'g'));
var result = chunks.map(function(chunk) {
return chunk.split('').reverse().join('');
}).join('');
Homework or not, here is a good use case to start with strings.
Here is a C approach but you have more in Javascript.
In fact you want to reverse by chunk so deal with chunk. How to create a chunk of string ? a way is to use slice https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/slice
var str = "abcdef";
console.log(str.slice(0,2));
So you have an easy way to slice your string into chunk.
Then you have to iterate over it, there is no good way of doing it actually there is dozen but you could do it from backward to the beginning of the string:
for( i=str.length ; i>0 ; i -= k ){
// i will go from the end of your str to
// the beginning by step of k(=3) and you can use i - k and i
// to slice your string (as we see it before)
// you have to take care of the last part that could be less than
// 3
}
then you have to format the result, the most easy way to do that is to concatenate results into a string here it is :
var strRes = "";
strRes += "res 1";
strRes += "res 2";
console.log(strRes); // should screen "res 1res 2"
As it is homework, I wont make a jsfiddle, you have here all the pieces and it's up to you to build the puzzle.
hope that help
$(function() {
var n = 'reversestrings', k = 3;
var revString = "";
for (var i =0; i<=n.length; i++) {
if (i%k == 0) {
l = parseInt(k) + parseInt(i);
var strChunk = n.substring(i,l);
var innerStr = "";
for (var j =0; j<strChunk.length; j++) {
var opp = parseInt(strChunk.length) - parseInt(j) - 1;
innerStr = innerStr + strChunk.charAt(opp);
}
revString = revString + " "+innerStr;
}
}
alert(revString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
My take on this. Pure JS without even built-in functions:
function reverseSubStr(str) {
var right = str.length - 1, reversedSubStr = '';
while(right >= 0) {
reversedSubStr += str[right];
right--;
}
return reversedSubStr;
}
function reverseStr(str) {
var initialStr = str, newstr = '', k = 3, substr = ''
for(var i = 1; i <= initialStr.length; i++) {
substr += initialStr[i - 1]; // form a substring
if(i % k == 0) { // once there are 3 symbols - reverse the substring
newstr += reverseSubStr(substr) + " "; // ... and add space
substr = ''; // then clean temp var
}
}
return newstr += substr; // add the remainder of the string - 'gs' - and return the result
}
var str = 'reversestrings';
console.log(reverseStr(str)); //ver sre tse nir gs
I like #Jozef 's approch but here is mine as well for those who are not much into Regex -
//Taking care of Tail Calling
function reverStrInChunk(str, k, r=''){
let index=0, revStr,
res = str.substring(index, k), remStr;
revStr = res.split("").reverse().join("");
remStr = str.substring(k, str.length);
r = r + revStr;
if(remStr.length>k){
return reverStrInChunk(remStr,k, r+" ");
}
else if(remStr.length<k) {
return r +" "+remStr;
}else{
return r +" "+ remStr.split("").reverse().join("");
}
}
var aStr = reverStrInChunk('reversestrings',3);//ver sre tse nir gs
console.log(aStr);

Accessing JavaScript var's each char and adding back-slash n to divide string in 2 lines

I am trying to divide my string in 2 lines if string is greater than 15 characters, so i am finding a space after 15 char and putting /n to string so that when var gets printed it should get printed in 2 lines.
following is my JavaScript code. its not working, please if anyone can help.
Thankyou
var name = row.product_name;
var val = 15;
var output;
var flag = false;
console.log(name[0]);
for(i=0; i<row.product_name.length; i++)
{
if(i > val)
{
if(name[i] == ' ')
{
name[i] = "/n";
flag = true;
}
}
if(flag)
{
val = val + 15;
flag = false;
}
}
this can't work because javascript strings are immutable, so you can't reassign name[i]. You have to use replace, slice, split, or other operations on the whole string
var myString = "jsdjposjgiohg squg oiq oih osqdh uh hsquv hup h opsdqh voph";
myStringA=myString.split(" ");
var newString="";
var n=0;
for (var i=0;i<myStringA.length;i++){
n+=myStringA[i].length;
if (n>15){
n=0;
newString+=myStringA[i]+"\n";
}else{
newString+=myStringA[i]+" ";
}
}
console.log(newString);
Strings are immutable in javascript so you need to put the changes in a new variable
Also the newline character is \n not /n
var name = row.product_name;
var val = 15;
var output = "";
var flag = false;
console.log(name[0]);
for(i=0; i<row.product_name.length; i++)
{
output += name[i]
if(i > val)
{
if(name[i] == ' ')
{
output[i] = "\n";
flag = true;
}
}
if(flag)
{
val = val + 15;
flag = false;
}
}

Javascript Unicode Conversion and Search

I'm wondering whether anyone has any insight on converting an array of character codes to Unicode characters, and searching them with a regex.
If you have
var a = [0,1,2,3]
you can use a loop to convert them into a string of the first four control characters in unicode.
However, if you then want to create a regex
"(X)+"
where X == the character code 3 converted to its Unicode equivalent, the searches never seem to work. If I check for the length of the string, it's correct, and .* returns all the characters in the string. But I'm having difficulties constructing a regex to search the string, when all I have to begin with is the character codes. Any advise?
Edit:
var a = [0,1,2,3,0x111];
str = "";
for(var i = 0; i < a.length; i++) {
str += String.fromCharCode(a[i]);
}
var r = [0x111]
var reg = ""
reg += "(";
for(var i = 0; i < r.length; i++) {
var hex = r[i].toString(16);
reg += "\\x" + hex;
}
reg += ")";
var res = str.match(RegExp(reg))[0];
Edit
//Working code:
var a = [0,1,2,3,0x111];
str = "";
for(var i = 0; i < a.length; i++) {
str += String.fromCharCode(a[i]);
}
var r = [3,0x111]
var reg = ""
reg += "(";
for(var i = 0; i < r.length; i++) {
var hex = r[i].toString(16);
reg += ((hex.length > 2) ? "\\u" : "\\x") + ("0000" + hex).slice((hex.length > 2) ? -4 : -2);
}
reg += ")";
var res = str.match(RegExp(reg))[0];
With changes to a few details, the example can be made to work.
Assuming that you are interested in printable Unicode characters in general, and not specifically the first four control characters, the test vector a for the string "hello" would be:
var a = [104, 101, 108, 108, 111]; // hello
If you want to match both 'l' characters:
var r = [108, 108]
When you construct your regular expression, the character code must be in hexadecimal:
reg += "\\x" + ("0" + r[i].toString(16)).slice(-2);
After that, you should see the results you expect.

javascript - how to break up a string every X amount of characters?

How do I break up a string every X amount of characters? For example, I'd like to break up a very long string every 1000 characters, and the string could be completely random everytime.
var string = <my text string that is thousands of characters long>
You could use Regex:
'asdfasdfasdfasdf'.match(/.{3}|.{1,2}/g); // 'asd', 'fas', etc.
Replace 3 with 1000 of course.
Here's a contrived example: http://jsfiddle.net/ReRPz/1/
As a function:
function splitInto(str, len) {
var regex = new RegExp('.{' + len + '}|.{1,' + Number(len-1) + '}', 'g');
return str.match(regex );
}
That RegExp really only needs to be created once if you have a set number to split like 1000.
Try this function:
function getParts(str, len)
{
var res = [];
​while (str.length) {
res.push(str.substring(0, len));
str = str.substring(len);
}
return res;
}
var s = "qweasedzxcqweasdxzc12";
console.log(getParts(s, 10));
​
i would use substring function on string
str = //the given string
arr = [];
for(i=0;i<str.length;i+=1000)
{
s = i;
// if the last string is less than 1000chars
e = (str.length - i) > 1000 ? (i+1000) : (str.length - i);
arr.push = str.substring(s,e);
}
Here's a way to do it recursively:
var string = "my text string that is thousands of characters long";
var arr = [];
function div( str, len ) {
if( str.length < len )
return arr.push(str);
else
arr.push(str.substring(0,len))
div( str.substring(len), len );
}
div( string, 5 );
for( var i = 0; i < arr.length; i++ ) {
document.write( arr[i] + "<br/>");
}
/* output:
my te
xt st
ring
that
is th
ousan
ds of
char
acter
s lon
g
*/
Like this:
var myString = "my text string that is thousands of characters long";
var myCurrentString = "";
var myBrokenUpString = new Array();
for(var i = 0; i < myString.length; i++) {
myCurrentString += myString.charAt(i);
if(i % 1000 == 0) {
myBrokenUpString.push(myCurrentString);
myCurrentString = "";
}
if(i + 1 == myString.length) myBrokenUpString.push(myCurrentString);
}
Please note that the above code is untested and may contain errors.
You can then POST the array and piece it back together on the other end. The piecing-together-code would look something like this:
var myRestoredString = "";
for(var i = 0; i<myBrokenUpString.length; i++) {
myRestoredString += myBrokenUpString[i];
}
Borrowing the idea from Joe Tuskan:
var str = 'asdfasdfasdfasdf';
var len = 3;
var regex = new RegExp(".{"+len+"}", "g");
var trail = str.length - (str.length % len);
var parts = str.match(regex);
parts.push(str.substring(trail));
document.write(parts.join('<br>'));
http://jsfiddle.net/6aSHB/1/

What's the most efficient algorithm to find the indexes of multiple characters inside a string (javascript)?

I'm looking for the fastest method I can use to search a body of text for the indexes of multiple characters.
For example:
searchString = 'abcdefabcdef';
searchChars = ['a','b'];
// returns {'a':[0,6], 'b':[1,7]}
You should be able to use a regular expression to find all occurances of each character. Something like:
function findIndexes(find, str) {
var output = {};
for (var i = 0; i < find.length; i++) {
var m = [];
var r = new RegExp('.*?' + find[i], 'g');
var ofs = -1;
while ((x = r.exec(str)) != null) {
ofs += x[0].length;
m.push(ofs);
}
output[find[i]] = m;
}
return output;
}
Edit:
Did some changes, and now it works. :) However, as Javascript doesn't have a matches method to get all matches at once, it's not really any improvment over using indexOf... :P
Edit 2:
However, you can use a regular expression to find any of the characters, so you only need to loop the string once instead of once for each character. :)
function findIndexes(find, str) {
var output = {};
for (var i = 0; i < find.length; i++) output[find[i]] = [];
var r = new RegExp('.*?[' + find.join('') + ']', 'g');
var ofs = -1;
while ((x = r.exec(str)) != null) {
ofs += x[0].length;
output[x[0].substr(x[0].length-1,1)].push(ofs);
}
return output;
}
Assuming few letters to search for and many letters to search against (i.e. low number of letter, long strings), the latter is the most efficient, since you only go through the string once, and then test each letter.
The other one goes through the string as many times as there are letters to search for.
After timing a few single pass algorithms and Guffa's regex, I ended up going with this:
function findIndexesMultiPass(str,find) {
var x, output = {};
for (var i = 0; i < find.length; i++) {
output[find[i]] = [];
x = 0;
while ((x = str.indexOf(find[i], x)) > -1) {
output[find[i]].push(x++);
}
}
return output;
}
var searchString = "abcd abcd abcd";
var searchChars = ['a', 'b'];
var result = findIndexesMultiPass(searchString, searchChars);
// {'a':[0,5,10], 'b':[1,6,11]}
This turned out to be pretty slow:
function findIndexesOnePass(str,find) {
var output = {};
for (var i = 0; i < find.length; i++) {
output[find[i]] = [];
}
for (var i = 0; i < str.length; i++) {
var currentChar = str.charAt(i);
if (output[currentChar] !== undefined) {
output[currentChar].push(i);
}
}
return output;
}
var searchString = "abcd abcd abcd";
var searchChars = ['a', 'b'];
var result = findIndexesOnePass(searchString, searchChars);
// {'a':[0,5,10], 'b':[1,6,11]}
Rough times (indexes of 3 characters)
Google Chrome (Mac)
findIndexesMultiPass: 44ms
findIndexesOnePass: 799ms
findIndexesRegEx: 95ms
Safari
findIndexesMultiPass: 48ms
findIndexesOnePass: 325ms
findIndexesRegEx: 293ms
Firefox
findIndexesMultiPass: 56ms
findIndexesOnePass: 369ms
findIndexesRegEx: 786ms

Categories