javascript replace character with loop - javascript

This should be simple but I am not sure why it isn't working:
function kebabToSnake (str){
var string = "";
var chart = "";
for(i=0; i < str.lenght; i++){
if (str.charAt(i) == "-") {
chart = "_";
string = string + chart;
}
else {
chart = str.charAt(i);
string = string + chart;
}
}
return string
}
I know I could do it with str.replace(/-/g,"_") but I cannot see what's wrong with the above, besides being too long. Any help would be great.

You spelled "length" wrong. ( on line 4 )
It works after the spelling correction.
function kebabToSnake (str){
var string = "";
var chart = "";
for(i=0; i < str.length; i++){ //fixed spelling from 'str.lenght'
if (str.charAt(i) == "-") {
chart = "_";
string = string + chart;
}
else {
chart = str.charAt(i);
string = string + chart;
}
}
return string
}
var body = document.querySelector( 'body' ),
output = kebabToSnake( '-' ); //First test with '-' in conditional statement
body.innerHTML = output; //display to body
output = kebabToSnake( 'Another String' ); //Second test with random text triggering ELSE statement
body.innerHTML += '<br>' + output; //display to body

You can achieve this goal by using RegExp more concisely:
function kebabToSnake (str) {
return str.replace(/-/g, '_');
}

Related

How to filter Cyrillic words in gmail using Google App Script

please help!
My goal is to filter the gmail inbox messages with Google App Script and find the specified Cyrillic word in it.
For example, I have a function that parse the messages:
var parseRawContent = function(rawContent)
{
var lines = rawContent.split("\n");
var result = {};
var headers = {};
var body = "";
var currentHeaderKey = null;
var headerParsed = false;
for (var i = 0; i < lines.length; i++) {
if (lines[i].trim() === "") {
if (headers.date === undefined) {
continue;
}
headerParsed = true;
continue;
}
if (!headerParsed) {
var headerParts = lines[i].match(/^([-a-z]+):(.*)/i);
if (headerParts) {
currentHeaderKey = headerParts[1].toLowerCase();
headers[currentHeaderKey] = headerParts[2].trim();
} else {
// Header continues on new line
headers[currentHeaderKey] += " " + lines[i].trim();
}
} else {
body += lines[i];
}
}
if (headers["content-transfer-encoding"] === "base64") {
try {
body = Utilities.newBlob(Utilities.base64Decode(body)).getDataAsString();
} catch (err) {
getLogger().log("Could not base64 decode body.")
}
}
result.headers = headers;
result.body = body;
return result;
};
Also, I have a function to spot the Russian text in the raw messages:
function(m, raw) {
"Has 'привет' in body"
return raw.body.match(/привет/i)
},
All the code above is taken from (https://github.com/spamzero/spamzero/blob/master/spam-zero.js)
Problem: the match does not happen.
What might be an issue?
Thank you
UPD: I found following issues with parsing the Gmail messages/threads
Russian text can be encoded with "Quoted Printable" encoding;
Russian text can be encoded with "Base64" encoding;
To manage all above the following changes were made for the original functions.
Parse function:
var parseRawContent = function(rawContent) {
var lines = rawContent.split("\n");
var result = {};
var headers = {};
var body = "";
var currentHeaderKey = null;
for (var i = 0; i < lines.length; i++) {
// Checking that the line is a header (starts with "<something>:")
var headerParts = lines[i].match(/^([-a-z]+):(.*)/i);
if (headerParts) {
currentHeaderKey = headerParts[1].toLowerCase();
headers[currentHeaderKey] = headerParts[2].trim();
} else {
// Decode Quoted-Printable to UTF-8 if applicable
if (headers["content-transfer-encoding"] === "quoted-printable") {
// check that the line is started with "=A0" or similar:
if (lines[i].match(/^=[0-9A-H]{2}=(.*)/)) {
try {
lines[i] = lines[i].replace(/=\s$/g, ''); // Replace the last "="
lines[i] = lines[i].replace(/={1}/g, '%'); // Replace all the "=" with "%" for decodeURI method
lines[i] = lines[i].split(" "); // Split the line into the words divided by space
var DecodedLine = ""
for (var j = 0; j < lines[i].length; j++) {
var SubLines = "";
SubLines = decodeURI(lines[i][j]);
DecodedLine += SubLines;
}
lines[i] = DecodedLine;
} catch (err) {
getLogger().log("Could not quoted-printable decode body.")
}
} else {
continue
}
}
// Decode base64 to UTF-8 if applicable
if (headers["content-transfer-encoding"] === "base64") {
try {
lines[i] = Utilities.newBlob(Utilities.base64Decode(lines[i])).getDataAsString();
} catch (err) {
getLogger().log("Could not base64 decode body.")
}
}
// Add everything that is not a header incl. decoded lines to BODY
body += lines[i];
}
}
result.headers = headers;
result.body = body;
return result;
};
Spot function:
function(m, raw) {
"Has Russian words 'тест' or 'привет' in body"
var matchers = [/тест/i, /привет/i
]
for (var i = 0; i < matchers.length; i++) {
if (raw.body.match(matchers[i])) {
return true;
}
}
},
An issue has been closed.
P.S.: I am a noob in coding. Please do not hesitate to comment/suggest more efficient solution.

How to find a word in a string?

The challenge is to "find Waldo." I'm trying to figure out how to find a word in a function/string." Return the index of where in the string 'Waldo' starts."
function findWaldo(str) {
var waldoPosition;
return waldoPosition
}
Simple task to do:
function findWaldo(str) {
return str.indexOf("waldo"); //the string you are looking for
}
It is explained quite well here.
There should be a library that does it easily, like string.indexOf, but you can do it manually with this algorithm:
int count = 0;
string yourText = "This is waldo?";
string toSearch = "waldo";
for (int x = 0; x < yourText.Lenght; x++)
{
if(yourText[x] == toSearch[0])
if((count + 1) == toSearch.Lenght)
return x;
else
count = 0;
//here we'd say ehh there's not Waldo on the string
}
To find a word or letter you can use x.indexOf method, hope to below code helps.
// Question
const findWord = (str, findWord) =>{
let total = ""
let error = false
let errorMessage = "";
if(str != null && str != ""){
error = false
if(!str.indexOf(findWord)){
total = `there is no ${findWord} in str peremeter.
`
}else{
total = `the position of ${findWord} is ${str.indexOf(findWord)}`
}
}else{
error = true;
errorMessage = "Please fill the str perimeter."
return errorMessage
}
return total
}
// Calling Function
console.log(findWord("Hello World", "World"))

Limiting length of each word in a string

Is there a way to limit the length of each word in a string?
For example:
Loop through each word in a string
If a word is longer than X amount of characters, display a pop up message and do not submit the form.
Edit: My final code:
$("#comment-form").submit(function(event) {
var str = $("#comment-box").val(), limit = 135;
var wordList = str.split(' ');
$(wordList).each(function(i, word) {
if(word.length > limit) {
alert("Your comment has a string with more than " + limit + " characters. Please shorten it.");
event.preventDefault();
}
});
});
Try this:
var str = "This is the test string that contains some long words";
var wordList = str.split(' ');
var limit = 4;
$(wordList).each(function(i, word){
if(word.length >= limit){
alert(word);
}
});
You can use the following function
<script>
var string = "Please be sure question to answer the question";
function checkWordLength(string)
{
var string_array = string.split(" ");
for(var i=0; i<string_array.length; i++)
{
var word = string_array[i];
var word_length = word.length;
if(word_length>6) return false;
}
}
checkWordLength(string);
</script>
jsFiddle
function CheckString(string, character_limit)
{
var word = /\w+/igm;
var match;
while((match = word.exec(string)) !== null) {
if(match[0].length > character_limit)
{
alert(match[0]);
return false;
}
}
return true;
}
var character_limit = 5;
var string = 'this is a string of words and stuff even';
CheckString(string, character_limit);
This example uses regular expressions when it returns false make sure to either return false from the onSubmit method of your form.

String URL to json object

I was trying to make a JSON Object from a String URL without success
i have this:
var URL = "http://localhost/index.php?module=search&param1=4";
i need this:
var dir = index.php;
var result = {
module:'search',
param1:4
};
Can anyone help me with the code?
It's not entirely correct to post a link here, but in this case what OP needed is just some library to parse urls.
And here it is: http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
This function can parse variables AND arrays from a string URL:
function url2json(url) {
var obj={};
function arr_vals(arr){
if (arr.indexOf(',') > 1){
var vals = arr.slice(1, -1).split(',');
var arr = [];
for (var i = 0; i < vals.length; i++)
arr[i]=vals[i];
return arr;
}
else
return arr.slice(1, -1);
}
function eval_var(avar){
if (avar[1].indexOf('[') == 0)
obj[avar[0]] = arr_vals(avar[1]);
else
obj[avar[0]] = avar[1];
}
if (url.indexOf('?') > -1){
var params = url.split('?')[1];
if(params.indexOf('&') > 2){
var vars = params.split('&');
for (var i in vars)
eval_var(vars[i].split('='));
}
else
eval_var(params.split('='));
}
return obj;
}
In your case:
obj = url2json("http://localhost/index.php?module=search&param1=4");
console.log(obj.module);
console.log(obj.param1);
Gives:
"search"
"4"
If you want to convert "4" to an integer you have to do it manually.
This simple javascript does it
url = "http://localhost/index.php?module=search&param1=4";
var parameters = url.split("?");
var string_to_be_parsed = parameters[1];
var param_pair_string = string_to_be_parsed.split("&");
alert(param_pair_string.length);
var i = 0;
var json_string = "{"
for(;i<param_pair_string.length;i++){
var pair = param_pair_string[i].split("=");
if(i < param_pair_string.length - 1 )
json_string += pair[0] + ":'" + pair[1] + "',";
else
json_string += pair[0] + ":'" + pair[1] + "'";
}
json_string += "}";
alert(json_string);

.read .write .replace string elements in jQuery

I have these 2 functions (serialize and deserialize) in Javascript (below) and I want to change it to jQuery. I am wondering what would the right replacement for read and write in jQuery. Read and write strings are from and to a Textarea. This is part of Openlayers vector formats, getting geometries into / from OL map canvas.
Serialize is outputing the geometries from mapcanvas to textarea.
function serialize(feature) {
var type = document.getElementById("formatType").value;
var pretty = document.getElementById("prettyPrint").checked;
var str = formats['out'][type].write(feature, pretty);
str = str.replace(/,/g, ', ');
document.getElementById('output').value = str;
}
Deserialize is reading string from Textarea into OL mapcanvas.
function deserialize() {
var element = document.getElementById('text');
var type = document.getElementById("formatType").value;
var features = formats['in'][type].read(element.value);
var bounds;
if(features) {
if(features.constructor != Array) {
features = [features];
}
for(var i=0; i<features.length; ++i) {
if (!bounds) {
bounds = features[i].geometry.getBounds();
} else {
bounds.extend(features[i].geometry.getBounds());
}
}
vectors.addFeatures(features);
map.zoomToExtent(bounds);
var plural = (features.length > 1) ? 's' : '';
element.value = features.length + ' feature' + plural + ' added';
} else {
element.value = 'Bad input ' + type;
}
}
Thanks in advance.
Again, I am asking about the read and write function equivalent in jQuery. These 2 lines:
var str = formats['out'][type].write(feature, pretty);
var features = formats['in'][type].read(element.value);
to get the text in a text area
$("#myTextArea").val();
To set it to something
$("#myTextArea").val("Foo bar.");

Categories