So I have my code like this:
for (var i = 0; i < str.length; i++) {
str = str.replace("|", "Math.abs(");
str = str.replace("|", ")");
}
Is there anyway to get the same effect using a regex?
Or at least a regex with a function?:
str = str.replace(/?/g, function() {?});
You can use this single regex replace method:
str = str.replace(/\|([^|]+)\|/g, 'Math.abs($1)');
RegEx Demo
You can match the string between |s and then replace them with whatever string you want
str[i] = str[i].replace(/\|(.*?)\|/g, "Math.abs($1)");
For example,
var str = ["|1|", "|-2|+|22 * -3|"];
for (var i = 0; i < str.length; i++) {
str[i] = str[i].replace(/\|(.*?)\|/g, "Math.abs($1)");
}
console.log(str);
# [ 'Math.abs(1)', 'Math.abs(-2)+Math.abs(22 * -3)' ]
Related
Given the string below:
"Hello this is a :sample string :hello"
I want to substitute :sample and :hello with something else. How can I do this in JavaScript?
This is what I tried:
var sentence = "Hello this is a :sample string :hello";
var words = sentence.split(" ");
for (var i = 0; i < words.length; i++) {
if (words[i].startsWith(":")) {
words[i] = words[i] + ":";
}
}
sentence = words.join(" ");
console.log(sentence)
Use String.replace(). It can accept specific strings or regular expressions.
I'm wondering whether anyone has any insight on converting an array of character codes to Unicode characters, and searching them with a regex.
If you have
var a = [0,1,2,3]
you can use a loop to convert them into a string of the first four control characters in unicode.
However, if you then want to create a regex
"(X)+"
where X == the character code 3 converted to its Unicode equivalent, the searches never seem to work. If I check for the length of the string, it's correct, and .* returns all the characters in the string. But I'm having difficulties constructing a regex to search the string, when all I have to begin with is the character codes. Any advise?
Edit:
var a = [0,1,2,3,0x111];
str = "";
for(var i = 0; i < a.length; i++) {
str += String.fromCharCode(a[i]);
}
var r = [0x111]
var reg = ""
reg += "(";
for(var i = 0; i < r.length; i++) {
var hex = r[i].toString(16);
reg += "\\x" + hex;
}
reg += ")";
var res = str.match(RegExp(reg))[0];
Edit
//Working code:
var a = [0,1,2,3,0x111];
str = "";
for(var i = 0; i < a.length; i++) {
str += String.fromCharCode(a[i]);
}
var r = [3,0x111]
var reg = ""
reg += "(";
for(var i = 0; i < r.length; i++) {
var hex = r[i].toString(16);
reg += ((hex.length > 2) ? "\\u" : "\\x") + ("0000" + hex).slice((hex.length > 2) ? -4 : -2);
}
reg += ")";
var res = str.match(RegExp(reg))[0];
With changes to a few details, the example can be made to work.
Assuming that you are interested in printable Unicode characters in general, and not specifically the first four control characters, the test vector a for the string "hello" would be:
var a = [104, 101, 108, 108, 111]; // hello
If you want to match both 'l' characters:
var r = [108, 108]
When you construct your regular expression, the character code must be in hexadecimal:
reg += "\\x" + ("0" + r[i].toString(16)).slice(-2);
After that, you should see the results you expect.
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);
}
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