How to add the looped value inside string.match? - javascript

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

Related

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

JavaScript trim character

I want to delete "()" from each value. How would I do that?
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++){
console.log(arr[i]);
}
Since all the other answers are unnecessarily complicated, here's a simple one:
arr = arr.map(s => s.slice(1, -1));
You can do it in-place too if you prefer; the important part is .slice(1, -1), which takes a substring starting from the character at index 1 (the second character) and ending before the last character (-1).
String.prototype.slice documentation on MDN
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++){
var arrLength = arr[i].length -2;
var shortArr = arr[i].substr(1,arrLength);
console.log(shortArr);
}
This gets one character less on the front and back
use replace
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++){
var x = arr[i];
x = x.replace(/[()]/g,"");
console.log(x);
}
note:
i dedited, because alexander was right
so u need to use regex, "g" for search globally,
"[" "]" to find all character inside
This is fast and should work no matter how many parenthesis are in the string, it will remove them all.
arr[i] = arr[i].split(/\(|\)/g).join("");
This matches ( followed by anything that isn't ) followed by ). Would also fail for "(test(ing)123)", (if you care)
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++) {
arr[i] = arr[i].replace(/\(([^)]+)\)/g, "$1");
}
This is much more simple/faster (but arguably more brittle):
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++) {
arr[i] = arr[i].substr(1, arr[i].length - 2);
}

How do I duplicate every letter in a string with JS

I'm trying to double my string xyz to xxyyzz in JS but can't get it to return correctly. What am I doing wrong?
<script>
string=["xyz"];
for (var i=0;i<string.length;i++)
{
document.write(string[i]*2);
}
</script>
var string = "xyz".split('').map(function(s){return s+s}).join('');
I like doing it using array maps instead of for loops. It seems cleaner to me.
The correct way would be to add the strings together (concatenation) instead of using a multiply by 2 which won't work. See below:
<script type="text/javascript">
var string = ['xyz'];
for (var i = 0, len = string.length; i < len; i++) {
document.write(string[i] + string[i]);
}
</script>
A few problems:
You've declared string inside an array, giving string.length a value of 1 as that's the number of elements
You can't multiply strings, unfortunately. You need to concatenate them
Here's how I'd do it:
var string = "xyz";
var newString = "";
for (var i = 0; i < string.length; i++)
newString += string[i] + string[i];
document.write(newString);
You didn't declared a string, you declared an array of string with 1-length.
Your are multiplying position of array (string[i]*2), trying concatenating (string[i] + string[i]).
This should work:
var string = 'xyz';
for (var i = 0, len = string.length; i < len; i++) {
document.write(string[i] + string[i]);
}

Split comma-separated list and prepend character to each value

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

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