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);
}
Related
Sorry I'm fairly new at javascript
My current output, from user inputing 'what a beautiful day':
what
abea
utif
ulda
y
how can I take the first letter of each word to get an output of something like this:
wauuy hbtl aeid tafa
I tried this:
var output = '';
var counter = 0;
var newStr2 = newStr.split('\n');
for (let i = 0; i < newStr2.length; i++) {
output = output + newStr2[counter].substr(0,1)
counter++
}
Is there a way maybe to read rows and columns? that way I can take first letter of every row then column
Thanks.
You can achieve using two for loops. One for each letter in the word and one for each element of the array(no of words).
var newStr = `what
abea
utif
ulda
y`
var output = '';
var newStr2 = newStr.split('\n');
for(var j = 0; j < newStr2[0].length; j++) {
for (let i = 0; i < newStr2.length; i++) {
if(newStr2[i][j]) {
output = output + newStr2[i][j];
}
}
output += ' ';
}
console.log(output);
UPDATE:
The if condition is to check whether some word has that no of characters. For example, last word contains only one character(y). Therefor in new output it prints undefined for other places. So we check whether the word contains a character in that index and if not just ignores. Check the following code and you will understand better.
var newStr = `what
abea
utif
ulda
y`
var output = '';
var newStr2 = newStr.split('\n');
for(var j = 0; j < newStr2[0].length; j++) {
for (let i = 0; i < newStr2.length; i++) {
output = output + newStr2[i][j];
}
output += ' ';
}
console.log(output);
Use a regular expression to split every 4th character of the input (sans spaces) into an array, then use reduce to combine them together:
function transform(input) {
const wordCount = input.split(' ').length;
const chunked = input.replace(/ /g, '')
.match(new RegExp('\\w{1,' + wordCount + '}', 'g'));
const output = chunked.reduce((accum, chunkWord) => {
[...chunkWord].forEach((char, i) => (
accum[i] = (accum[i] || '') + char
));
return accum;
}, {});
return output;
}
console.log(transform('what a beautiful day'));
console.log(transform('foo foo bar bar'));
console.log(transform('fooo bar baz'));
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(" ");
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 do I break up a string every X amount of characters? For example, I'd like to break up a very long string every 1000 characters, and the string could be completely random everytime.
var string = <my text string that is thousands of characters long>
You could use Regex:
'asdfasdfasdfasdf'.match(/.{3}|.{1,2}/g); // 'asd', 'fas', etc.
Replace 3 with 1000 of course.
Here's a contrived example: http://jsfiddle.net/ReRPz/1/
As a function:
function splitInto(str, len) {
var regex = new RegExp('.{' + len + '}|.{1,' + Number(len-1) + '}', 'g');
return str.match(regex );
}
That RegExp really only needs to be created once if you have a set number to split like 1000.
Try this function:
function getParts(str, len)
{
var res = [];
while (str.length) {
res.push(str.substring(0, len));
str = str.substring(len);
}
return res;
}
var s = "qweasedzxcqweasdxzc12";
console.log(getParts(s, 10));
i would use substring function on string
str = //the given string
arr = [];
for(i=0;i<str.length;i+=1000)
{
s = i;
// if the last string is less than 1000chars
e = (str.length - i) > 1000 ? (i+1000) : (str.length - i);
arr.push = str.substring(s,e);
}
Here's a way to do it recursively:
var string = "my text string that is thousands of characters long";
var arr = [];
function div( str, len ) {
if( str.length < len )
return arr.push(str);
else
arr.push(str.substring(0,len))
div( str.substring(len), len );
}
div( string, 5 );
for( var i = 0; i < arr.length; i++ ) {
document.write( arr[i] + "<br/>");
}
/* output:
my te
xt st
ring
that
is th
ousan
ds of
char
acter
s lon
g
*/
Like this:
var myString = "my text string that is thousands of characters long";
var myCurrentString = "";
var myBrokenUpString = new Array();
for(var i = 0; i < myString.length; i++) {
myCurrentString += myString.charAt(i);
if(i % 1000 == 0) {
myBrokenUpString.push(myCurrentString);
myCurrentString = "";
}
if(i + 1 == myString.length) myBrokenUpString.push(myCurrentString);
}
Please note that the above code is untested and may contain errors.
You can then POST the array and piece it back together on the other end. The piecing-together-code would look something like this:
var myRestoredString = "";
for(var i = 0; i<myBrokenUpString.length; i++) {
myRestoredString += myBrokenUpString[i];
}
Borrowing the idea from Joe Tuskan:
var str = 'asdfasdfasdfasdf';
var len = 3;
var regex = new RegExp(".{"+len+"}", "g");
var trail = str.length - (str.length % len);
var parts = str.match(regex);
parts.push(str.substring(trail));
document.write(parts.join('<br>'));
http://jsfiddle.net/6aSHB/1/
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