Get words from a string pattern in Javascript - javascript

I am trying to get words from a string dynamically using a pattern. The pattern and input look something like this
var pattern = "hello this is %var% using %var%";
var input = "hello this is nick using javascript";
Now I want to be able to have an array of the variables like this
["nick", "javascript"]

This should do it:
var pattern = "hello this is %var% using %var%";
var input = "hello this is nick using javascript";
var re = new RegExp(pattern.replace(/%var%/g, '([a-z]+)'));
var matches = re.exec(input).slice(1); // <-- ["nick", "javascript"]
The variable re is a RegExp whose pattern is the pattern variable with each instance of %var% replaced with a capturing group of lower case letters (extend if necessary).
matches is then the result of the re regex executed on the input string with the first element removed (which will be the full matching string).

var pattern = "hello this is %var% using %var%";
var input = "hello this is nick using javascript";
var outputArr = [];
pattern.split(" ").forEach(function (e, i){
e === "%var%" ? outputArr.push(input.split(" ")[i]) : "";
});
outputArr is the desired array.

Related

replace characters in a string using an associative array mapping

I have an associative array/object such at this:
mymap = {'e':'f', 'l':'g'};
And I want to replace all matching characters in a string using the above as a simple cypher, but only replacing existing characters. As an example,
input = "hello world";
output = input.map(mymap); //how can I do this?
//output is "hfggo worgd"
Balancing performance (for large input) and code size are of interest.
My application is replacing unicode characters with latex strings using this map, but I'm happy to stick with the more general question.
The following works:
mymap = {'e':'f', 'l':'g'};
var replacechars = function(c){
return mymap[c] || c;
};
input = "hello world";
output = input.split('').map(replacechars).join('');
although having to split and then join the input seems quite round-about, particularly if this is applied to a wall of text.
Another way would be loop over the object properties and use regex for each replacement:
var input = 'hello world';
var output = '';
for (var prop in mymap) {
if (mymap.hasOwnProperty(prop)) {
var re = new RegExp(prop, 'g');
output = input.replace(re, mymap[prop]);
}
}

Javascript pattern for test from input value

What I want is simple. I have an input field and I want to check what items from an unordered list (ul) contain the input's value.
So, I have this:
$('input#search').keyup(
function() {
var value = $(this).val();
if (value.length > 0) {
var patt = /value/g;
console.log(patt);
$('ul#list li').filter(function() {
return (patt.test($(this).html()));
});
}
}
);
My problem here is that if, for example, the value of the input is 'abcd' patt will be /value/g instead of /abcd/g so I want to know how can I insert the value in the pattern.
To create a pattern based on dynamic data you'd use the RegExp ctor passing it a string of the pattern. e.g.
var word = 'foo';
var re = new RegExp(word, 'g'); // var re = /foo/g
Don't forget to escape characters with special meaning in regexp.
However, if you're just looking for a simple "is x within y" comparison, indexOf can perform this check very quickly:
var sample = 'this is a foo sentence';
var loc = 'Hello, world!'.indexOf('world') // 7
then simply check if indexOf(...) != -1.
define patt as new RegExp
var patt = new RegExp(value,"g")

matching values stored in variables or array with string javascript regex

Im trying to find a patterns in the sentence for regex matching.. in the code below result contains a string and we are checking if the word apple is present in it.
var patt = /apple/gi;
var newResult = patt.test(result);
I found the above code from a used case.. But i was wondering if i have more than one values and i want to check it in the string result, lets say an array with values var arr=["apple", "orange"] var patt=/arr[0]/gi will not work.. what could be the way in that scenario??
To check multiple entries, you can use the OR operator:
var patt = /apple|orange/gi;
var newResult = patt.test(result);
if you have a variable, you can do the below, IF(!) your key is regexp safe of course (that is, it doesn't contains characters which have meaning in regexp syntax):
var key = "apple";
var patt = new RegExp(key, 'gi');
var newResult = patt.test(result);
Although in this case, you might as well use indexOf:
var key = "apple";
var newResult = result.indexOf(key) > -1;
To use a string for your regex expressions, you need to create the regex using the regex constructor.
var pattern = "apple|orange";
var regex = new RegExp(pattern, "g"); // g is for global match
Read more about it here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

How to match multiple sequences

How is it possible to match more than one string with regular expressions?
Here I want to match both name and txt, but only name is matched?
var reg = new RegExp('%([a-z]+)%', "g");
reg.exec('%name% some text %txt%');
You need to use String.match instead of exec:
'%name% some text %txt%'.match(reg);
Use match instead:
'%name% %txt%'.match(reg); //["%name%", "%txt%"]
exec only retrieves the first match (albeit with capturing groups).
If the capturing groups are important to you, you can use a loop:
var matches = [];
var str = '%name% some text %txt%';
var reg = new RegExp('%([a-z]+)%', "g");
while (match = reg.exec(str)){
matches.push(match);
}
If you only want to keep the captured groups, use this instead:
matches.push(match[1]);
The g flag does work but needs to be executed on the same string multiple times
var reg = new RegExp('%([a-z]+)%', "g");
var str = '%name% some text %txt%';
var result;
while( result = reg.exec( str ) ) { // returns array of current match
console.log( result[1] ); // index 0 is matched expression. Thereafter matched groups.
}​
The above outputs name & txt to the console.
Example here

Get integer from inside parentheses

I have a string where I'm trying to grab the integer inside. The string looks like:
"(2) This is a string"
I need to grap that 2. but it could be any number so I tried:
var str = "(2) this is a string";
var patt = /\(\d\)/;
var num = str.match(patt);
This doesn't return the correct answer. Should I do a split on the () or is there a better regexp?
var str = "(2) this is a string";
var patt = /\((\d)\)/;
var num = str.match(patt)[1];
2 things. When you want to capture a segment form a matched string, you use () to note that. So I just wrapped the \d in parens to capture it.
Second, in order to access the captured segments, you must drill into the returned array. the match method will return an array where the first item is the entire matched string, and the second item is any matched capture groups. So use [1] to fetch the first capture group (second item in array)
Use this. doesnt matter how many parenthesis
var str = "(2) this is a string";
var patt = /\(\d\)/;
var num = str.match(patt)[0].replace("(", "").replace(")","")
This should work
var str = "(2) this is a string";
var a = /\([\d]*\)/g.exec(str)[0];
var num = a.substring(1, a.length-1);
var str = "(2) this is a string";
var patt = /\((\d+)\)/;
alert(str.match(patt)[1]);
This works!
Why it works. Because inside the (()) mayhem there's also a capture which populates the [1] elements in the matches array.

Categories