Camelcase using split( ) twice in Javascript - javascript

I am trying to make a function to split a sentence into words then split the words into characters and capitalize the first letter of each word. Yes it's homework and after many tries I can not get it to work. One thing tripping me up is using split() twice.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<head>
<title>Sentence Case Conversion</title>
<script type= "text/javascript">
/* <![CDATA[ */
/* ]]> */
</script>
</head>
<body>
<form name= "convertText">
<p>Enter text to convert to sentence case:</p>
<input type ="text" size ="120" name="userInput">
</br>
</br>
<input name= "Submit" onclick= "sentenceCase()" value= "Convert Text" type= "button">
</form>
</br>
</br>
</br>
<form name= "ouputText">
<p>Here is your converted text:</p>
<input type="text" size="120" name="result">
<script type= "text/javascript">
/* <![CDATA[ */
function sentenceCase() {
var userInput = document.forms[0].userInput.value; //get user input
var wordArray = userInput.split(" "); //split user input into individual words
for (var i=0; i<wordArray.length; i++) {
var characterArray = wordArray[i].split("");
characterArray[0].toUpperCase();
wordArray[i]=characterArray.join;
}
/* ]]> */
</script>
</body>
</html>

You're close:
> characterArray[0].toUpperCase();
That returns a value, it doesn't modify it in place
> wordArray[i]=characterArray.join;
join is a method, you have to call it. Also, it returns a value, it doesn't modify anything in place. You might consider using substring instead, but with the array you have:
var firstChar = characterArray.shift().toUpperCase();
var newWord = firstChar + characterArray.join('');
should do the trick.

toUpperCase() can't modify your variable in place; it returns the capitalized string. So:
characterArray[0] = characterArray[0].toUpperCase();
... but you could just use charAt() and substring(), too:
wordArray[0] = wordArray[0].charAt(0).toUpperCase() + wordArray[0].substring(1);
... and then you have to actually call join():
wordArray[i] = characterArray.join();
... and you'd probably want to pass that an empty string, or it'll default to a comma as a separator.
The fun way is 'hello world this is camel case'.replace(/\s(\S)/g, function($0, $1) { return $1.toUpperCase(); }), though.

Factor out the common elements into understandable pieces of code:
function toCamelCase(sentence) {
var words = sentence.split(" ");
var length = words.length;
for (var i = 1; i < length; i++)
words[i] = capitalize(words[i]);
return words.join("");
}
function capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
Now you can convert sentences to upper case. It's probably a good idea to remove punctuation marks from the sentence before converting it. Here are a few examples:
alert(toCamelCase("java script")); // javaScript
alert(toCamelCase("json to XML")); // jsonToXML
alert(toCamelCase("ECMA script")); // ECMAScript
The last one appears to be PascalCase but is still considered valid camelCase. You can see the demo here: http://jsfiddle.net/GhKmf/

Related

How to convert hexadecimal number into a text string (unicode, not just ASCII) (like PHP's hex2bin) in JavaScript?

Let us say that I have a text string that was converted into hexadecimal with PHP. For example:
<?php
$text = 'hello world';
$text_hex = bin2hex($text);
echo $text_hex; //echos 68656c6c6f20776f726c64
echo '<br>';
echo hex2bin($text_hex); //echos hello world
?>
How do I convert $text_hex, which will be a hexadecimal number, into a text string in JavaScript (just like the function hex2bin() in PHP).
So far I have only found ways to convert the hexadecimal number into a binary number, but not ways to interpret that binary number as a text string. So, for example, I managed to make this:
<script>function hex2bin(hex){
var resultado = (parseInt(hex, 16).toString(2));
return resultado;
};</script>
<div id="test">
</div>
hex2bin, write an hexadecimal number here:<br>
<input type="text" id="textinput" oninput="document.getElementById('test').innerText = hex2bin(document.getElementById('textinput').value)"><br>
<code> hello world = 68656c6c6f20776f726c64</code>
But that binary number is managed as a number, and I don't get how to interpret it as a text string.
How could I do it?
Edit:
Thank you very much to Bharata and to Laurence Mommers for their proposed solutions. They work but only with ascii characters. When it is tried to use others like ñ, ÿ, æ, ç, œ, it does not work. I tried even defining the charset as UTF-8 and as latin1 just in case that was the issue but it is not changing anything.
<script>function hex2bin(hex){
var resultado = (parseInt(hex, 16).toString(2));
return resultado;
};
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
};
function hexToString(hex)
{
return hex.match(/../g).map(function(v)
{
// "+" symbol is for converting from string to integer
return String.fromCharCode(+('0x'+v));
}).join('')
};
</script>
Original failed script UTF-8:
<div id="test" charset="UTF-8">
</div>
Laurence Mommers's script UTF-8:
<div id="test1" charset="UTF-8">
</div>
Bharata's script UTF-8:
<div id="test2" charset="UTF-8">
</div>
Original failed script ISO-8859-1:
<div id="test3" charset="ISO-8859-1">
</div>
Laurence Mommers's script ISO-8859-1:
<div id="test4" charset="ISO-8859-1">
</div>
Bharata's script ISO-8859-1:
<div id="test5" charset="ISO-8859-1">
</div>
<br>Write an hexadecimal number here:<br>
<input type="text" id="textinput" oninput="document.getElementById('test').innerText = hex2bin(document.getElementById('textinput').value); document.getElementById('test1').innerText = hex2a(document.getElementById('textinput').value); document.getElementById('test2').innerText = hexToString(document.getElementById('textinput').value); document.getElementById('test3').innerText = hex2bin(document.getElementById('textinput').value); document.getElementById('test4').innerText = hex2a(document.getElementById('textinput').value); document.getElementById('test5').innerText = hexToString(document.getElementById('textinput').value)"><br>
<code> php bin2hex('hello world') = 68656c6c6f20776f726c64</code>
<br>
<code> php bin2hex('ñ, ÿ, æ, ç, œ') = c3b12c20c3bf2c20c3a62c20c3a72c20c593</code>
My guess is that the method fromCharCode() is using a different charset to the one that php is using. Perhaps there is a way to make it use the charset that php uses? Or to make the hexadecimal conversion to the charset of javascript? Does this charset varies per browser?
You could try this solution:
function hexToString(hex)
{
return hex.match(/../g).map(function(v)
{
// "+" symbol is for converting from string to integer
return String.fromCharCode(+('0x'+v));
}).join('')
}
var text_hex = '68656c6c6f20776f726c64';
console.log(hexToString(text_hex)); //hello world
This should also work for non ascii characters. the decodeURIComponent(escape(x)) solution is not the nicest solution, but it is the only way i know of for converting to UTF-16
<div id="test"></div>
<script>
function hex2a(hexx) {
var hex = hexx.toString(); // Force string conversion
var array = [];
for (var i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2)
array.push(parseInt(hex.substr(i, 2), 16));
return decodeURIComponent(escape(String.fromCharCode.apply(null, array)));
}
document.getElementById('test').innerText = hex2a("c3b12c20c3bf2c20c3a62c20c3a72c20c5932c2068656c6c6f20776f726c64");
</script>
The encoding of the php ouput is utf-8 : 0xc3, 0xb1 -> U+00F1 = 'ñ'.
To decode a string containing a sequence of hexadecimal pairs in javascript you can insert a '%' before each pair of hexadecimal characters (with regex), and then parse the new string with decodeURIComponent which decode escaped utf-8 sequences to string characters :
function hex2string(hex)
{
try {
return decodeURIComponent((hex || '').replace(/([0-9A-Fa-f]{2})/g, '%$1'));
}
catch (URIError) {
return '\ufffd';
}
}
Here a code snippet to test hex2string :
<script>
function hex2string(hex)
{
try {
return decodeURIComponent((hex || '').replace(/([0-9A-Fa-f]{2})/g, '%$1'));
}
catch (URIError) {
return '\ufffd';
}
}
</script>
<div id="test">
</div>
<br>Write an hexadecimal number here:<br>
<input type="text" id="textinput" oninput="document.getElementById('test').innerText = hex2string(document.getElementById('textinput').value)"><br>
<code> php bin2hex('hello world') = 68656c6c6f20776f726c64</code>
<br>
<code> php bin2hex('ñ, ÿ, æ, ç, œ') = c3b12c20c3bf2c20c3a62c20c3a72c20c593</code>

Uncaught ReferenceError: Invalid left-hand side in assignment. Javascript

I want to replace a character in a string (original) with another string.
I am getting an error on running the debugger.
I dont understand what is wrong with the syntax.
<!DOCTYPE>
<html>
<head>
<title>HI there</title>
<meta lang="english">
</head>
<body>
<div>
Enter the original string<input id="original" value="" type="text"> <br>
Enter the replacing string<input id="replacing" value="" type="text"><br>
Enter the location to be replaced<input id="tobereplaced" value="" type="text"><br>
</div>
<br>
<button type="submit" onclick="replace()">Submit</button>
<br> Here you go the replaced string is:
<script>
function replace() {
var original = document.getElementById("original").value;
var replacing = document.getElementById("replacing").value;
var tobereplaced = document.getElementById("tobereplaced").value;
var replaced = "";
var originalLength = original.length;
var tobereplacedLength = tobereplaced.length;
var k = 0;
for (var i = 0; i < originalLength; i++) {
replaced.charAt(k) = original.charAt(i)
if (original.charAt(i) == replacing.charAt(0)) {
replaced = replaced + tobereplaced;
k = k + tobereplacedLength;
i++;
}
k++;
}
document.getElementById("replaced").innerHTML = replaced;
}
</script>
<h1 id="replaced"></h1>
</body>
</html>
you are trying to change the character of an empty string at line no:28 [replaced.charAt(k) = original.charAt(i)] this is the issue.
Also there are some unwanted increment in the code. please find the corrected below
I have updated the code below with // comment the code and added correct code. its working
// var k = 0; //Commented
// debugger; //Commented
for (var i = 0; i < originalLength; i++) {
if (original.charAt(i) == replacing.charAt(0)) {
replaced = replaced + tobereplaced;
// k = k + tobereplacedLength; //Commented
// i++; //Commented
} else{
replaced = replaced + original.charAt(i);
}
// k++; //Commented
}
Here is a more simplistic approach to the problem. It takes advantage of the .split() & .join() functions rather than using a for loop.
function replace() {
// set original string
var original = document.getElementById("original").value, // << use commas so you don't have to keep typing var
// set replacing string
replacing = document.getElementById("replacing").value,
// initialize newval
newValue,
// set replace position - this could also be called index
replacePosition = document.getElementById("tobereplaced").value; // << end variable declarations with semicolon
// split original string into array of characters
var splitOriginal = original.split("");
// use replacePosition as index value of character to replace
// & replace that character with replacing value
splitOriginal[replacePosition] = replacing;
// join array to form new string value
newValue = splitOriginal.join("");
document.getElementById("replaced").innerHTML = newValue;
}
<html>
<head>
<title>HI there</title>
<meta lang="english">
</head>
<body>
<div>
Enter the original string
<input id="original" value="" type="text">
<br>Enter the replacing string
<input id="replacing" value="" type="text">
<br>Enter the location to be replaced
<input id="tobereplaced" value="" type="text">
<br>
</div>
<br>
<button type="submit" onclick="replace()">Submit</button>
<br>Here you go the replaced string is:
<h1 id="replaced"></h1>
</body>
</html>

How do I print the result of a search() method in JavaScript?

I posted a question earlier regarding a school problem I was working on. I have what I believe to be the correct function per the assignment, but I am stuck. I need to have the alert() in my code display the index position of the substring it is searching for. Everything else works but I don't know how to send that info back to a variable that I can print to the screen. My code is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lesson 6 Application Project A</title>
<script language="JavaScript" type=text/javascript>
<!--
/*****************************************************************************
The placeholders sub and string are used to pass as arguments the
user's entry into the text box and the textarea. The variable where
is assigned the result of a method which returns the index (integer)
of the first occurence of sub (the string the program is searching for).
Start the search at the beginning of string (the text that is being searched).
Since the string is zero based, add 1 is to get the correct position of sub.
*****************************************************************************/
function search(sub, string) {
var where;
if (string.search(sub) != -1){
where = alert("Your index position is: " + where);
}
else{
where = alert("Could not find your string!");
}
}
//-->
</script>
</head>
<body>
<h3>CIW JavaScript Specialist</h3>
<hr />
<form name="myForm">
<p>
<strong>Look for:</strong>
<input type="text" name="what" size="20" />
</p>
<p>
<strong>in this string:</strong>
<textarea name="toSearch" rows="4" cols="30" wrap="virtual">
</textarea>
</p>
<p>
<input type="button" value="Search"
onclick="search(myForm.what.value, myForm.toSearch.value);" />
</p>
</form>
</body>
</html>
Try this
function search(sub, string) {
var where = string.indexOf(sub);
if (where != -1){
alert("Your index position is: " + where);
}
else{
alert("Could not find your string!");
}
}
Your where variable should be assinged to the result of the search.
function search(sub, string) {
var where = string.search(sub);
if (where != -1){
alert("Your index position is: " + (where + 1));
}
else{
alert("Could not find your string!");
}
}
My solution to my own problem was to create a variable called position and set it to receive the index position of the substring. I could then add that into my alert() and display the results to the screen. Corrected code is as follows:
function search(sub, string) {
var where;
var position = string.search(sub);
if (string.search(sub) != -1){
where = alert("Your index position is: " + position);
}
else{
where = alert("Could not find your string!");
}
}

Removing lines containing specific words in javascript

This script is supposed to take a list of links, transform some by changing some words and eliminate others containing specific string of characters.
The first part is ok. I need help with the second. The line
x = x.replace(/^.+/category/.+$/mg, "");
doesn't work even if we change the + with *. I used sources from here (1 & 2 ). So, help the noob.
<!DOCTYPE html>
<html>
<body>
<h3>Instert your links</h3>
input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
http://example.com/category/fashion.html
http://example.com/ad/8910.html
http://example.com/category/sports.html
</textarea>
<button type="button" onclick="myFunction()">Get clean links</button>
<p id="links"></p>
<script>
function myFunction() {
x = document.getElementById("myTextarea").value;
x = x.replace(/http:\/\/example.com\/ad\//g, "http://example./com/story/");
x = x.replace(/\n/g,"</br>");
x = x.replace(/^.+/category/.+$/mg, "");
document.getElementById("links").innerHTML = x;
}
</script>
</body>
</html>
I think you need to escape your forward slashes as you are also using them as the regex delimiter.
x = x.replace(/^.+\/category\/.+$/mg, "");
Assuming that you want to copy those lines in <p> remove line containing category in it.
change your function to
function myFunction() {
x = document.getElementById("myTextarea").value;
var lines = x.split("\n").filter( function(val){
return val.indexOf( "category" ) == -1;
});
document.getElementById("links").innerHTML = lines.join( "<br>" );
}

search() function of Javascript does not behave properly

I don't know why search() function returns 0 for any input with SPECIAL CHARACTER, I wanted to find position of 1st occurrence of special character. When I am hardcoding the value for search() method it is working fine, but when I am taking value from text box it is not working properly.
Following is my HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<input type="text" id="txt" onkeyup="return checkLength();"/>
<input type="button" id="btn" value="Verify" onclick="getValue()"/>
</body>
</html>
Following is the script where I have implemented the use of search() of Javascript, but don't know why I am getting 0 value for any input. Actually I wanted to find the position of first special character occurrence.
$(document).ready(function() {
$('#btn').attr('disabled',true);
$("#txt").bind({
paste : function(){
$('#btn').attr('disabled',false);
checkLength();
},
cut : function(){
checkLength();
}
});
});
function checkLength(){
var txtLength = $("#txt").val().length;
var banTxt = document.getElementById("txt").value;
if (txtLength != 0) {
if(isAlphaNumeric(document.getElementById("txt").value)) {
$('#btn').attr('disabled',false);
} else {
var str=banTxt;
//Here I am using search() to find position of Special Character.
var n=banTxt.search(/[^a-zA-Z ]/g);
alert("position of special char is: " + n);
var preTxt = banTxt.substring(0,(txtLength - 1));
var preTxtLength = preTxt.length;
alert("Special characters are not allowed!");
if(preTxtLength == 0){
$('#btn').attr('disabled',true);
document.getElementById("txt").value = "";
}else if(preTxtLength != 0){
document.getElementById("txt").value = preTxt;
$('#btn').attr('disabled',false);
}
}
} else {
$('#btn').attr('disabled',true);
}
}
function isAlphaNumeric(inputString) {
return inputString.match(/^[0-9A-Za-z]+$/);
}
function getValue(){
var txtValue = document.getElementById("txt").value;
alert("Value submitted is: " + txtValue);
}
var n=banTxt.search(/[^a-zA-Z ]/g);
I tried with string with special characters like 123#4$5 , 12#4 , etc. and I am getting alert as position of special char is: 0
That's just what your regex matches: No alphabet characters and no blanks - that includes digits. In contrast, your isAlphaNumeric function matches against /^[0-9A-Za-z]+$/ - you probably want to align them with each other.
Actually i have used the following line var n=banTxt.search(/[^a-zA-Z ]/g); for getting the position of special char, at the same time please note that i have used onkeyup event so if i am copy pasting the code i.e first ctrl then v, ctrl + v then ctrl itself is keyup event i think this might be the reason i am getting 0 as position of special char, as after pressing ctrl no text is pasted but onkeyup event is triggered.
I am looking for the solution of it.

Categories

Resources