javascript modify subindex of string array - javascript

I'm trying to change subindex of string array but it's not modifing.There is the jsbin link.
function LetterCapitalize(str) {
var arr = str.split(" ");
var nstr = "";
for (var i = 0; i < arr.length; i++) {
var ltr = arr[i][0];
console.log('ltr: ' + ltr.toUpperCase());
arr[i][0] = ltr.toUpperCase();
nstr += arr[i] + " ";
}
str = nstr.trim();
console.log("result: " + str);
return str;
}
LetterCapitalize("hello world");

You could try something like the following:
function LetterCapitalize(str) {
var arr = str.split(" ");
var nstr = "";
for(var i=0; i<arr.length; i++){
arr[i] = arr[i][0].toUpperCase()+arr[i].slice(1);
nstr+= arr[i] + " ";
}
str = nstr.trim();
console.log("result: " + str);
return str;
}
console.log(LetterCapitalize("hello world"));
The line that does the difference is the following:
arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1);
What we are doing here is to capitalize the first letter of the string at arr[i] and then concatenate the capitalized letter with the rest letters.

That's because (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Character_access):
For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable.
I.e. strings are immutable.

You could as well just use string.replace matching the first char in each word, using a callback function to upper case the character.
Something like this.
var str = "hello world";
var newStr = str.replace(/\b(\w)/g, function(chr) {
return chr.toUpperCase()
})
console.log(newStr)

Related

How to insert an alphabet/digit at specific location of string?

I am supposed to write a JavaScript function which inserts the character/s between only two consecutive Hash (#) symbols. For an example: If input string is:
var str = "#TIME##MONEY#";
Then output string must be "#TIME#IS#MONEY#"
You can use the replace() method.
var str = "#TIME##MONEY#";
var insert = 'IS'
var newstr = str.replace('##', '#'+insert+'#')
console.log(newstr);
Splice the string where you find ## and concat the string
var str = "#TIME##MONEY#";
for (i = 0; i < str.length; i++) {
if (str[i] == '#' && str[i + 1] == '#') {
newStr = str.slice(0, i+1) + 'abc'
+str.slice(i + 1, str.length);
}
}
console.log(str)
console.log(newStr)
Just use replace
// Once
var str = "#TIME##MONEY#";
document.write(str.replace('##','#IS#'));
//more than once
var str2 ="#TIME##MONEY##TIME##MONEY#";
while(str2.indexOf('##') != -1)
{
str2 = str2.replace('##','#IS#');
}
document.write('<br />'+str2);

Replace character at string index

Why won't this code work for me below? Can't i reassign a value at a specific index in the string?
function replaceChar (str) {
let i
for (i = 0; i < str.length; i++) {
if (str[i] == '-') {
str[i] = ' '
}
}
return str
}
Strings are immutable in JavaScript. You have to create a new string instead:
str = str.substring(0, i) + ' ' + str.substring(i + 1);
If you're doing that a lot, you might convert the string to an array of characters, do the replacements, and then convert the array back into a string. Here's an ES2015+ example:
function replaceChar(str) {
return [...str].map(ch => ch === "-" ? " " : ch).join("");
}
console.log(replaceChar("testing-1-2-3"));
Your entire loop can be replaced by the replace method:
str = str.replace(/-/g, " ");
Strings are immutable in Javascript - you can't change individual characters. If you want to do something like that, you'll have to explicitly convert the string to an array first, perform your changes, and then join the array back into a string again:
function replaceChar (str) {
str = [...str];
let i
for (i = 0; i < str.length; i++) {
if (str[i] == '-') {
str[i] = ' '
}
}
return str.join('');
}
console.log(replaceChar('foo-bar-baz'));
You can use split() and join() together. Split the string by - and join the array by <space>
str.split("-").join(" ");

How do you capitalize the first letter in a string?

I am learning JavaScript and I am disappointed that the below code doesn't work. It is still a lowercase "i". I was trying to capitalize every letter in the string (hence the for loop) but I wanted to stop and address what was going wrong.
str = 'i ran there';
for(var i = 0; i<str.length; i++){
if(i===0){
str[i] = str[i].charAt(0).toUpperCase();
}
}
console.log(str);
Can someone please describe what is going wrong here?
whats going wrong here is strings in javascript are immutable.
You can't change them. What you can do is create a new string with the change.
If I understand your question, you could do it with something like -
var str = 'i ran there';
var arr = str.split(" ");
var div = document.getElementById("out");
for(var i = 0; i < arr.length; i++){
// The First letter
// arr[i] = arr[i].substring(0,1).toUpperCase() + arr[i].substring(1);
// Every letter
arr[i] = arr[i].toUpperCase();
div.innerHTML += arr[i] + "<br />";
}
<div id="out"></div>
As for what is going on in your code, you can't modify the array backing the String (assuming it is an array) like that.
You are asking for index i of a String str. Because str is a String, you cannot use index values to grab certain characters in the string - try console.log(str[0]) - it will return undefined.
To accomplish what you are trying to do, you would need to simply add to a new string after capitalizing each letter. Example:
str = 'i ran there';
capStr = ''
for(var i = 0; i < str.length; i++){
if(i === 0) capStr += str.charAt(i).toUpperCase();
else capStr += str.charAt(i);
}
console.log(capStr);
You have to create a new string because strings in javascript are immutable:
First get every word separated:
var arrayOfstrings = s.split(" ");
Then you can treat each string like there own word
Fancy way :
var capFirstLetter = arrayOfStrings[index].replace(/^./, function (match) {
return match.toUpperCase();
});
Which is just a regex. The /^./ means the first character in the string. And the rest is self explanatory.
Or this way:
var s = arrayOfStrings[index];
var s2 = s[0].toUpperCase()+ s.substr(0,1);
Or even this really lame way
var s = arrayOfStrings[index];
var newS = "";
for(var i = 0; i < s.length; i++){
if(i == 0) newS+= s[0].toUpperCase();
else newS+= s[i];
}
Of course all these can be done in a forloop to cap them all and put back together:
var s = "hello woorld hello world";
var arrayOfStrings = s.split(" ");
for(var i = 0; i < arrayOfStrings.length; i++){
arrayOfStrings[i]= arrayOfStrings[i].replace(/^./, function(match) {return match.toUpperCase();});
}
var s2 = arrayOfStrings.join(" ");

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);
}

Categories