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(" ");
Related
I have a string that need to be split with a regular expression for applying some modifications.
eg:
const str = "Hello+Beautiful#World";
const splited = str.split(/[\+#]/)
// ["Hello", "Beautiful", "World"]
Now the string has been split with + or #.
Now say after applying some modification to the items in the array, I have to join the array using the same separator that used to split, so the character + and # has to be in the same position as before.
eg: if i applied some modification string and joined. Then it should be.
Hello001+Beutiful002#World003
How can i do this?
When you place a pattern inside a capturing group, split will return the matched delimiters as even array items. So, all you need to do is modify the odd items:
var counter=1;
var str = "Hello+Beautiful#World";
console.log(
str.split(/([+#])/).map(function(el, index){
return el + (index % 2 === 0 ? (counter++ + "").padStart(3, '0') : '');
}).join("")
);
Don't use split and join in this case. Use String.replace(), and return the modified strings:
const str = "Hello+Beautiful#World";
let counter = 1;
const result = str.replace(/[^\+#]+/g, m =>
`${m.trim()}${String(counter++).padStart(3, '0')}`
);
console.log(result);
Another option, which might not fit all cases, is to split before the special characters using a lookahead, map the items, and join with an empty string:
const str = "Hello+Beautiful#World";
let counter = 1;
const result = str.split(/(?=[+#])/)
.map(s => `${s.trim()}${String(counter++).padStart(3, '0')}`)
.join('')
console.log(result);
You could get the missing substrings by iterating the splitted value and check the parts.
var string = "Hello++#+Beautiful#World",
splitted = string.split(/[\+#]+/),
start = 0,
symbols = splitted.map((s, i, { [i + 1]: next }) => {
var index = string.indexOf(next, start += s.length);
if (index !== -1) {
var sub = string.slice(start, index);
start = index;
return sub;
}
return '';
});
console.log(symbols);
console.log(splitted.map((s, i) => s + symbols[i]).join(''));
My solution is to get the splitters then save them into an array and rejoin:
function splitAndRejoin(){
const str = "Hello+Beautiful#World";
const splited = str.split(/[\+#]/);
var spliterCharacter = [];
for(var i = 0; i < str.length; i++){
if(str[i] == "+" || str[i] == "#"){
spliterCharacter.push(str[i]);
}
}
var rejoin = "";
for (i = 0; i <= spliterCharacter.length; i++) {
if(i< spliterCharacter.length)
rejoin += splited[i] + spliterCharacter[i];
else
rejoin += splited[i];
}
console.log(splited);
console.log(spliterCharacter);
console.log(rejoin); // Result
}
you can rejoin the array by finding the indexes that where the matching happened on the string
const str = "Hello+Beautiful#World";
const regex = /[\+#]/g;
const splited = str.split(regex);
console.log(splited);
//join
let x = '';
let i=0;
while ((match = regex.exec(str)) != null) {
x = x + splited[i] + "00" + (i+1) + str[match.index];
i++;
}
x = x + splited[splited.length-1] + "00" + (i+1);
console.log(x);
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);
I'm trying to solve this exercise which goal is to give me a string that has to be turned into another string. The characters of the new string are repeated like in the example below.
Example:
accum("abcd"); // "A-Bb-Ccc-Dddd"
I wrote the following code:
function accum(s) {
counter = 0;
for (var i = 0; i < s.length; i++) {
return s[i].toUpperCase() + s[i].repeat(counter) + "-";
counter += 1;
}
}
When I try to run a sample test such as ZpglnRxqenU I get this error:
Expected: 'Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu', instead got: 'Z-'.
Apparently the problem is linked to the loop which is not working, but I can't figure out why.
Here's an ES6 one-liner :
const accum = word => word.toLowerCase().split("").map( (letter,index) => letter.toUpperCase() + letter.repeat(index) ).join("-")
console.log( accum("ZpglnRxqenU") )
Explanation :
word.split("") Start with breaking your string into an array of letters
.map( (letter,index) => Iterate each letter, keeping track of the index as you go
letter.toUpperCase() + letter.repeat(index) Replace each letter with the transformed value that you return
At this point, you have an array of transformed values
.join("-") Join everything back to a string with "-" as a separator.
You can combine the use of the methods: String.prototype.split(), Array.prototype.map() and Array.prototype.join():
function accum(s) {
return s
.split('')
.map(function (e, i) {
return e.toUpperCase() + e.repeat(i);
})
.join('-');
}
console.log(accum('ZpglnRxqenU'));
ES6:
const accum = s => s.split('').map((e, i) => e.toUpperCase() + e.repeat(i)).join('-');
console.log(accum('ZpglnRxqenU'));
You can do this:
function accum(s) {
s = s.toLowerCase();
const letters = [];
for (let i = 0; i < s.length; i++) {
letters.push(s[i].toUpperCase() + s[i].repeat(i));
}
return letters.join('-');
}
console.log(accum('ZpglnRxqenU'));
You have an array and fill it with the letters, once filled you join the elements with '-'. You could just add the letters to a string but at the end you would have to trim the trailing '-', which isn't wrong but now you have 2 ways to do this.
Also you don't need the counter variable because i is already counting.
With array.reduce:
var str = "abcd";
function accum(str) {
var arr = str.split("");
return arr.reduce((m, o, i) => {
m += (i === 0 ? "" : "-") + o.toUpperCase() ;
for (var k = 0; k < i; k++) {
m += o;
}
return m;
}, "");
}
var ret = accum(str);
console.log(ret);
This should work for you. When you return the loop will stop. You need to remove that.
function accum(s) {
counter = 0;
sA = s.split('');
for (var i = 0; i < s.length; i++) {
sA[i] = sA[i].toUpperCase() + sA[i].toLowerCase().repeat(counter);
counter += 1;
}
return sA.join('-');
}
console.log(accum('ZpglnRxqenU'));
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)
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);
}