This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I want to have a 'newline'-function to pass a string to it and print it on pdf. my function so far is
var array = new Array();
function newLineFunction_PDF(text) {
var arr = text.replace(/.{70}\S*\s+/g, "$&#").split(/\s+#/);
return arr;
}
array = newLineFunction_PDF('some Text');
for( var i in array) {
print(array[i]);
}
What it does is cut the text in to pieces of length-70 incl. the last word, push it into the array and print it afterwards with new lines. Now i want to pass a number to the function, like 100, so i can decide the max-length of the text per line.
So far I tried:
function newLineFunction_PDF(text, num) {
var re = new RegExp(/.{num}\S*\s+/g);
var arr = text.replace(re, "$&#").split(/\s+#/);
return arr;
}
but I dont know how and where to add escapes into the new RegExp.
The parameter of Regexp is a string:
var re = new RegExp('.{' + num + '}\S*\s+', 'g');
Related
This question already has answers here:
How to get function parameter names/values dynamically?
(34 answers)
Closed 3 years ago.
I am trying to split the following string:
delete(value1,value2);
I want to get the values and save them in a array:
var values = [value1,value2]
A regex would do the trick:
/\((.*)\)/g.exec('delete(value1,value2);')[1].split(',')
This captures anything between parentheses, which you can then split again.
You can split the string using split function
var str = "delete(value1,value2)";
var stringArray = str.split("(");
var values=stringArray[1].split(",");
use Replace method to finally delte ")" from second string in array
values[1]=values[1].replace(")","");
How about:
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(fnStr) {
var fnStr = fnStr.replace(STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
if(result === null)
result = [];
return result;
}
var str = "delete(value1,value2)";
getParamNames(str);
This question already has answers here:
Splitting a string into chunks by numeric or alpha character with JavaScript
(3 answers)
Closed 5 years ago.
I'd like to split strings like
'foofo21' 'bar432' 'foobar12345'
into
['foofo', '21'] ['bar', '432'] ['foobar', '12345']
Is there an easy and simple way to do this in JavaScript?
Note that the string part (for example, foofo can be in Korean instead of English).
Second solution:
var num = "'foofo21".match(/\d+/g);
// num[0] will be 21
var letr = "foofo21".match(/[a-zA-Z]+/g);
/* letr[0] will be foofo.
Now both are separated, and you can make any string as you like. */
You want a very basic regular expression, (\d+). This will match only digits.
whole_string="lasd行書繁1234"
split_string = whole_string.split(/(\d+)/)
console.log("Text:" + split_string[0] + " & Number:" + split_string[1])
Check this sample code
var inputText = "'foofo21' 'bar432' 'foobar12345'";
function processText(inputText) {
var output = [];
var json = inputText.split(' '); // Split text by spaces into array
json.forEach(function (item) { // Loop through each array item
var out = item.replace(/\'/g,''); // Remove all single quote ' from chunk
out = out.split(/(\d+)/); // Now again split the chunk by Digits into array
out = out.filter(Boolean); // With Boolean we can filter out False Boolean Values like -> false, null, 0
output.push(out);
});
return output;
}
var inputText = "'foofo21' 'bar432' 'foobar12345'";
var outputArray = processText(inputText);
console.log(outputArray); Print outputArray on console
console.log(JSON.stringify(outputArray); Convert outputArray into JSON String and print on console
This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I have to replace multiple words in a string.
my code is like this
var csku = "{len}";
var value = 5;
var finalPrice = "({con}*{len})+{wid}+{fixed_var}+{extra}+{sqft}+{len}";
console.log(finalPrice.replace(csku, value));
Using this code I got this solution
({con}*5)+{wid}+{fixed_var}+{extra}+{sqft}+{len}
but I want this
({con}*5)+{wid}+{fixed_var}+{extra}+{sqft}+5
I google it for replacing multiple words in the string using one call I find this
str.replace(/X|x/g, '');
Here / and g is used for multiple replace and in this format I have to add static word but in my code csku is not fixed so how can I replace all words in one call using variable
Using the code from the duplicate to create a Regex object using the variable
var csku = "{len}";
var value = 5;
var finalPrice = "({con}*{len})+{wid}+{fixed_var}+{extra}+{sqft}+{len}";
var re = new RegExp(csku, "g");
console.log(finalPrice.replace(re, value));
use new RegExp(cksu, 'g') to create a regular expression that'll match all cksu.
new RegExp('{len}', 'g') will return /{len}/g meaning all global matches.
so finalPrice.replace(new RegExp(cksu, 'g'), value) will replace all global matches of cksu with value.
var csku = "{len}";
var value = 5;
var finalPrice = "({con}*{len})+{wid}+{fixed_var}+{extra}+{sqft}+{len}";
console.log(finalPrice.replace(new RegExp(csku, 'g'), value));
Standart replace function change just first match. You can use this function:
function ReplaceAll(Source, stringToFind, stringToReplace) {
var temp = Source;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression Pattern With A Variable
function function1() {
var key = "name";
var sample = "param.name['key'] = name; param.name[i] = 1000; param.name1[i] = name1;";
var result = result.replace(/param.<<name>>\[(\d+)\]/g, 'parameter[prefix_$1]');
}
Expected result: parameter['prefix_key'] = name; parameter['prefix_i'] = 1000;
I cant add variable key into the replace function in regular expresssion.
Please help how to construct the regular expression in replace
You can make a regex out of a string by making a RegExp object:
var regex = new RegExp("param\\." + name + "\\[(\d+)\\]", "g")
var result = result.replace(regex, 'parameter[prefix_$1]');
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 6 years ago.
I'm trying to use javascript to do a regular expression on a url (window.location.href) that has query string parameters and cannot figure out how to do it. In my case, there is a query string parameter can repeat itself; for example "quality", so here I'm trying to match "quality=" to get an array with the 4 values (tall, dark, green eyes, handsome):
http://www.acme.com/default.html?id=27&quality=tall&quality=dark&quality=green eyes&quality=handsome
You can use a regex to do this.
var qualityRegex = /(?:^|[&;])quality=([^&;]+)/g,
matches,
qualities = [];
while (matches = qualityRegex.exec(window.location.search)) {
qualities.push(decodeURIComponent(matches[1]));
}
jsFiddle.
The qualities will be in qualities.
A slight variation of #alex 's answer for those who want to be able to match non-predetermined parameter names in the url.
var getUrlValue = function(name, url) {
var valuesRegex = new RegExp('(?:^|[&;?])' + name + '=([^&;?]+)', 'g')
var matches;
var values = [];
while (matches = valuesRegex.exec(url)) {
values.push(decodeURIComponent(matches[1]));
}
return values;
}
var url = 'http://www.somedomain.com?id=12&names=bill&names=bob&names=sally';
// ["bill", "bob", "sally"]
var results = getUrlValue('names', url);
jsFiddle