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
Related
How to loop through a string and add its value inside of regex in the match method. I'm getting null.
Tried with /'str[i]'/g and it also gives null.
var str = "helloWorld";
var regResult;
for (var i = 0; i < str.length; i++) {
regResult = str.match(/str[i]/g); //gives null
};
Right now your regular expression is matching str followed by a single character from the range i - one single i, meaning it will match stri. To match the variable i, try the following:
var str = "helloWorld";
var regResult;
for (var i = 0; i < str.length; i++) {
regResult = str.match(new RegExp('str' + i, 'g')); //gives null
};
Here we are creating a regular expression whose pattern contains the current value of the variable i. As an example, if i is 4 then the regular expression will be constructed as if you had simply given /str4/g to str.match.
EDIT
To reflect the edit made to the question, my new proposed solution is as follows:
var str = "helloWorld";
var regResult;
for (var i = 0; i < str.length; i++) {
regResult = str.match(new RegExp(str[i], 'g')); //gives null
};
This code differs from the above code in that it is reading the value i from str. For example if i is 4 and str[4] = "h", then the regular expression will be constructed as if you had simply given the value of str[4] to str.match: str.match(/h/g).
Probably you need just a little bit fix
var str = "helloWorld";
var regResult;
for (var i = 0; i < str.length; i++) {
regResult = str.match(new RegExp(str[i], 'g'));
console.log(regResult)
};
// static RegExp -> /str[i]/g is just equal "str[i]"
// dynamic RegExp -> new RegExp(str[i], "g") is str[i] h,e,l,l, ...
var str = "helloWorld";
var regResult;
for (var i = 0; i < str.length; i++) {
regResult = str.match(new RegExp(str[i], "g")); //gives null
console.log(regResult);
};
You need to use the new RegExp() constructor, so you can dynamically create the regex with the iterated string:
str.match(new RegExp(str[i],'g'))
But if you are trying to get an array of matches for every letter in the string you need to push the matches array in your regResult and not just keep overrding its value on every iteration:
regResult.push(str.match(new RegExp(str[i], 'g'))); //gives null
Demo:
var str = "helloWorld";
var regResult = [];
for (var i = 0; i < str.length; i++) {
regResult.push(str.match(new RegExp(str[i], 'g'))); //gives null
};
console.log(regResult);
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 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"));
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);
}