Split comma-separated list and prepend character to each value - javascript

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

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

Doubling each letter in a String in js

I need string Double each letter in a string
abc -> aabbcc
i try this
var s = "abc";
for(var i = 0; i < s.length ; i++){
console.log(s+s);
}
o/p
> abcabc
> abcabc
> abcabc
but i need
aabbcc
help me
Use String#split , Array#map and Array#join methods.
var s = "abc";
console.log(
// split the string into individual char array
s.split('').map(function(v) {
// iterate and update
return v + v;
// join the updated array
}).join('')
)
UPDATE : You can even use String#replace method for that.
var s = "abc";
console.log(
// replace each charcter with repetition of it
// inside substituting string you can use $& for getting matched char
s.replace(/./g, '$&$&')
)
You need to reference the specific character at the index within the string with s[i] rather than just s itself.
var s = "abc";
var out = "";
for(var i = 0; i < s.length ; i++){
out = out + (s[i] + s[i]);
}
console.log(out);
I have created a function which takes string as an input and iterate the string and returns the final string with each character doubled.
var s = "abcdef";
function makeDoubles(s){
var s1 = "";
for(var i=0; i<s.length; i++){
s1 += s[i]+s[i];
}
return s1;
}
alert(makeDoubles(s));
if you want to make it with a loop, then you have to print s[i]+s[i];
not, s + s.
var s = "abc";
let newS = "";
for (var i = 0; i < s.length; i++) {
newS += s[i] + s[i];
}
console.log(newS);
that works for me, maybe a little bit hardcoded, but I am new too))
good luck
console.log(s+s);, here s holds entire string. You will have to fetch individual character and append it.
var s = "abc";
var r = ""
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
r+= c+c
}
console.log(r)
var doubleStr = function(str) {
str = str.split('');
var i = 0;
while (i < str.length) {
str.splice(i, 0, str[i]);
i += 2;
}
return str.join('');
};
You can simply use one of these two methods:
const doubleChar = (str) => str.split("").map(c => c + c).join("");
OR
function doubleChar(str) {
var word = '';
for (var i = 0; i < str.length; i++){
word = word + str[i] + str[i];
};
return word;
};
function doubleChar(str) {
let sum = [];
for (let i = 0; i < str.length; i++){
let result = (str[i]+str[i]);
sum = sum + result;
}
return sum;
}
console.log (doubleChar ("Hello"));

Replace all chars with #, except for last 4

function maskify(cc) {
var dd = cc.toString();
var hash = dd.replace((/./g), '#');
for (var i = (hash.length - 4); i < hash.length; i++) {
hash[i] = dd[i];
}
return hash;
}
I am trying to replace all chars with # except for last 4. Why isn't it working?
You could do it like this:
dd.replace(/.(?=.{4,}$)/g, '#');
var dd = 'Hello dude';
var replaced = dd.replace(/.(?=.{4,}$)/g, '#');
document.write(replaced);
If you find the solution, try this trick
function maskify(cc) {
return cc.slice(0, -4).replace(/./g, '#') + cc.slice(-4);
}
To replace a character in a string at a given index, hash[i] = dd[i] doesn't work. Strings are immutable in Javascript. See How do I replace a character at a particular index in JavaScript? for some advice on that.
function maskify(cc) {
let arr = cc.split('');
for (let i = 0; i < arr.length - 4; i++){
arr[i] = '#';
}
return arr.join('');
}

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

JavaScript regular expression

I've some DOM node:
<p>[CROP:1049,160x608,557x897] [CROP:1055,264x501,513x461] Some text</p>
I've created regular expression:
var re = new RegExp("\[CROP:(\d+),(\d+)x(\d+),(\d+)x(\d+)\]", "ig");
But how can I get values from each (\d)?
As a result, I need to replace each [CROP:xxx] to <a> nodes like this:
How can it be done? Thanks.
You have to do this in 2 steps, I think there is no function to do this in one step:
match all the [CROP:...] blocks
match their inner parts
It would look like this:
function regex_func(pattern,text) {
var i, max, sub = [],
re = new RegExp(pattern, "ig"),
match = text.match(re);
if (match)
{
for (i=0, max=match.length; i<max; i++)
{
re = new RegExp(pattern, "i");
sub[i] = re.exec(match[i]);
}
}
return sub;
}
var text = "[CROP:1049,160x608,557x897] [CROP:1055,264x501,513x461] Some text",
pattern = "\\[CROP:(\\d+),(\\d+)x(\\d+),(\\d+)x(\\d+)\\]";
matches = regex_func(pattern,text);
for (var i=0, max=matches.length; i<max; i++) {
html = ''+matches[i][0]+'';
text = text.replace(matches[i][0],html);
}
document.write(text);
You can text it here: http://jsfiddle.net/inti/fVQgp/5/
Edit: added the html string generation part, and the replace.
Edit 2: created a function to handle this matching problem. Used it in the actual problem.
From the ECMA spec:
15.10.6.2 RegExp.prototype.exec(string)
Performs a regular expression match of string against the regular expression and returns an Array object containing the results of the match, or null if string did not match.
e.g. match_data = re.exec(str)
Then match_data[1], ... will have each of the values within the parens.
You can do var mymatch = re.exec("mystring"). The resulting variable will hold the text matched by the capturing parentheses.
EDIT: sorry, mymatch[0] contains the matched string, mymatch[1] the text matched by the first set of parenthses, etc.
The following will do what you are looking for
http://jsfiddle.net/Eb6b7/2/
I was unable to do this using a single RegEx, Here is the Javascript code from the link above:
var str = "[CROP:1,20x30,40x50] [CROP:9,8x00,400x500] [CROP:10,201x301,401x501] [CROP:100,21x31,41x51] some text";
var re1 = new RegExp(/\[CROP:(\d+),(\d+)x(\d+),(\d+)x(\d+)\]/ig);
var re2 = new RegExp(/\[CROP:(\d+),(\d+)x(\d+),(\d+)x(\d+)\]/);
var data1 = str.match(re1);
var data2 = str.match(re2);
// Example of RegEx 1
for(var i = 0; i < data1.length; i++)
$('#parsed_content1').append("<div>" +data1[i] + "</div>");
// Example of RegEx 2
for(var i = 0; i < data2.length; i++)
$('#parsed_content2').append("<div>" +data2[i] + "</div>");
// What you are looking for
for(var i = 0; i < data1.length; i++){
var data3 = data1[i].match(re2);
for(var j = 0; j < data3.length; j++)
$('#overall').append("<div>" +data3[j] + "</div>");
}
var paragraphs = document.getElementsByTagName('p');
for (var p = 0; p < paragraphs.length; p++){
var matches = paragraphs[p].innerHTML.match(/\[CROP:(\d+),(\d+)x(\d+),(\d+)x(\d+)\]/ig);
console.log('matches: ' + matches.length + ' found. (' + matches.join(';') + ')');
for (var m = 0; m < matches.length; m++){
var data = /\[CROP:(\d+),(\d+)x(\d+),(\d+)x(\d+)\]/i.exec(matches[m]);
console.log('data: ' + data + ' (' + data.length + ')');
var a = document.createElement('a');
a.href = '#';
a.className = 'myclass';
var attr = ['id','x1','x2','x3','x4'];
for (var at = 0; at < attr.length; at++){
a.setAttribute('data-'+attr[at],data[at+1]);
}
a.innerHTML = data.toString();
document.getElementsByTagName('body')[0].appendChild(a);
}
}
Something like that? Use <regex>.exec(<target>) to get the matches, then you can use setAttribute to append the data to the object.
Demo

Categories