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