Javascript Unicode Conversion and Search - javascript

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.

Related

Javascript - Regex - Replace every other match in string with different strings

So I have my code like this:
for (var i = 0; i < str.length; i++) {
str = str.replace("|", "Math.abs(");
str = str.replace("|", ")");
}
Is there anyway to get the same effect using a regex?
Or at least a regex with a function?:
str = str.replace(/?/g, function() {?});
You can use this single regex replace method:
str = str.replace(/\|([^|]+)\|/g, 'Math.abs($1)');
RegEx Demo
You can match the string between |s and then replace them with whatever string you want
str[i] = str[i].replace(/\|(.*?)\|/g, "Math.abs($1)");
For example,
var str = ["|1|", "|-2|+|22 * -3|"];
for (var i = 0; i < str.length; i++) {
str[i] = str[i].replace(/\|(.*?)\|/g, "Math.abs($1)");
}
console.log(str);
# [ 'Math.abs(1)', 'Math.abs(-2)+Math.abs(22 * -3)' ]

Why is this giving me an error?

Why is this code giving me the following error message?
TypeError: Object 97 has no method 'charCodeAt'
var str = "Caesar Cipher";
str = str.split("");
num = 2;
x = 0;
for (var i = 0; i < str.length; i++) {
x = 0;
while (x < num) {
if (str[i].charCodeAt(0) <= 122 && str[i].charCodeAt(0) >= 97) {
str[i] = str[i].charCodeAt()+x;
}
x++;
}
}
console.log(str);
Incase anyone was interested in my final result: http://jsfiddle.net/zackarylundquist/8L9b5/
The line:
str[i] = str[i].charCodeAt()+x;
Is converting the element in the array from a string to a number. A number doesn't have a charCodeAt() method, hence why you're getting the error. Use the following:
str[i] = str[i].charCodeAt()+x + "";
This will keep the element a string, and you will still be able to call the charCodeAt() method.
Couldn't help it, I know it doesn't solve the op's problem exactly, but here's a nice caesar implementation (fiddle: http://jsfiddle.net/z97HR/3/):
var str = ("CaesarCipher").toLowerCase(); // let's use only lowercase letters, no spaces
console.log(str);
var offset = 0;
var crypt = str.split("").map(function(letter){
var offsetLetter = 97 + (letter.charCodeAt(0) + offset - 97) % 26;
return String.fromCharCode(offsetLetter);
}).join("")
console.log(crypt);

Split comma-separated list and prepend character to each value

I would like to turn "one,two,three,four,five" into "$one $two $three $four $five".
Here is what I have so far to separate/explode the comma-separated list.
var str = 'one,two,three,four,five';
var str_array = str.split(',');
for(var i = 0; i < str_array.length; i++)
{
// Trim the excess whitespace.
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
// Add additional code here, such as:
alert(str_array[i]);
}
How can I prepend a character to each value and out them as space-separated list?
It would be great to turn the code into a function that can be applied to a string.
It is as simple as:
'$' + ('one,two,three,four,five'.split(',').join(' $'))
Here is a function that will do it, and output an empty string if there is no matches:
function (s) {
var a = s.split(',').join(' $');
return a ? '$' + a : '';
}
Use the + operator and join:
for(var i = 0; i < str_array.length; i++) {
str_array[i] = 'a' + str_array[i];
}
var out_str = str_array.join(' ');
Replace 'a' with whatever character you wish to prepend.
Also we can use replace()
var str = 'one,two,three,four,five';
var str_array = str.split(',');
for (var i = 0; i < str_array.length; i++) {
str = str.replace(',', '$');
}
alert('$' + str);

how to remove the spaces in an Array?

i am trying to create a program that stores words in an Array, what I've done is whatever the program finds a separator (" " or ",") it pushes it in the array, my problem here is that it store even the separators with it (i must use the array SEPARATORS).
var sentence = prompt("");
var tab = [];
var word = "" ;
var separators = [" ", ","];
for(var i = 0 ; i< sentence.length ; i++){
for(var j = 0 ; j < separators.length ; j++){
if(sentence.charAt(i) != separators[j] && j == separators.length-1){
word += sentence.charAt(i);
}else if(sentence.charAt(i) == separators[j]){
tab.push(word);
word = "";
}
}
}
tab.push(word);
console.log(tab);
You can try this:
var text = 'Some test sentence, and a long sentence';
var words = text.split(/,|\s/);
If you don't want empty strings:
var words = text.split(/,|\s/).filter(function (e) {
return e.length;
});
console.log(words); //["some", "test", "sentence", "and", "a", "long", "sentence"]
If you need to use the array you can try this:
var text = 'Some test sentence, and a long sentence',
s = [',', ' '],
r = RegExp('[' + s.join('') + ']+'),
words = text.split(r);
I would just use regex:
var words = sentence.split(/[, ]+/);
If you want to fix your code, use indexOf instead of a for loop:
for (var i = 0; i < sentence.length; i++) {
if (separators.indexOf(sentence.charAt(i)) === -1) {
word += sentence.charAt(i);
} else {
tab.push(word);
word = "";
}
}
After reexamining the problem, I think you need a combination of native string functions and the compact method from the excellent underscore library which removes 'falsy' entries in an array:
$('#textfield).keyup(analyzeString);
var words;
function analyzeString(event){
words = [];
var string = $('#textfield).val()
//replace commas with spaces
string = string.split(',').join(' ');
//split the string on spaces
words = string.split(' ');
//remove the empty blocks using underscore compact
_.compact(words);
}

Arrangement of two string charecters into one string using loop

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.

Categories