Using JavaScript & regex I want to split a string on every %20 that is not within quotes, example:
Here%20is%20"a%20statement%20"%20for%20Testing%20"%20The%20Values%20"
//easy to read version: Here is "a statement " for Testing " The Values "
______________ ______________
would return
{"Here","is","a statement ","for","Testing"," The Values "}
but it seems my regex are no longer strong enough to build the expression. Thanks for any help!
A way using the replace method, but without using the replacement result. The idea is to use a closure to fill the result variable at each occurence:
var txt = 'Here%20is%20"a%20statement%20"%20for%20Testing%20"%20The%20Values%20"';
var result = Array();
txt.replace(/%20/g, ' ').replace(/"([^"]+)"|\S+/g, function (m,g1) {
result.push( (g1==undefined)? m : g1); });
console.log(result);
Just try with:
var input = 'Here%20is%20"a%20statement%20"%20for%20Testing%20"%20The%20Values%20"',
tmp = input.replace(/%20/g, ' ').split('"'),
output = []
;
for (var i = 0; i < tmp.length; i++) {
var part = tmp[i].trim();
if (!part) continue;
if (i % 2 == 0) {
output = output.concat(part.split(' '));
} else {
output.push(part);
}
}
Output:
["Here", "is", "a statement", "for", "Testing", "The Values"]
Related
I want to search an element of an array of strings in a string. Like this:
let array:[String] = ["dee", "kamal"]
let str:String = "Hello all how are you, I m here for deepak."
so, I want
str.contain("dee") == true
any possible search in string?
You can do it in one line by composing a regular expression pattern "(item1|item2|item3)"
let array = ["dee", "kamal"]
let str = "Hello all how are you, I m here for deepak."
let success = str.range(of: "(" + array.joined(separator: "|") + ")", options: .regularExpression) != nil
You should iterate over the array and for each element, call str.contains.
for word in array {
if str.contains(word) {
print("\(word) is part of the string")
} else {
print("Word not found")
}
}
You can do like this:
array.forEach { (item) in
var isContains:Bool = str.contains(item)
print(isContains)
}
There is a strings as below:
2016,07,20,19,20,25
How can I transfer this strings to such as this format string:
2016-07-20 19:20:25
Thank you very much!
A solution with array slice could be this
let parts = [];
let date = "2016,07,20,19,20,25";
let formatted = ((parts = date.split(",")).slice(0,3)).join("-") + ' ' + parts.slice(3).join(":")
You could also do it with String#replace and a function as the 2 argument;
let date = "2016,07,20,19,20,25";
date.replace(/,/g, (() => {
let count = 0;
return (match, position) => {
count += 1;
if(count == 3) return ' ';
else if(count < 3) return '-';
else return ':';
});
})())
Note: Both approaches assume that the format will always be the one provided
6 numbers seperated by commas
I'm checking an array of strings for a specific combination of patterns. I'm having trouble using Meteor's Match function and regex literal together. I want to check if the second string in the array is a url.
addCheck = function(line) {
var firstString = _.first(line);
var secondString = _.indexOf(line, 1);
console.log(secondString);
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+#)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+#)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-]*)?\??(?:[\-\+=&;%#\.\w]*)#?(?:[\.\!\/\\\w]*))?)/g;
if ( firstString == "+" && Match.test(secondString, urlRegEx) === true ) {
console.log( "detected: + | line = " + line )
} else {
// do stuff if we don't detect a
console.log( "line = " + line );
}
}
Any help would be appreciated.
Match.test is used to test the structure of a variable. For example: "it's an array of strings, or an object including the field createdAt", etc.
RegExp.test on the other hand, is used to test if a given string matches a regular expression. That looks like what you want.
Try something like this instead:
if ((firstString === '+') && urlRegEx.test(secondString)) {
...
}
my regex query below does an exact match of a word say Bob or Bill for example
var regExp = new RegExp("^" + inputVal + "$", 'i');
what i want it to do is match anything exactly (Bob or Bill Etc) but not match Fred
so match anything exactly except for Fred, does that make sense?
anyone help me out as to how i do that?
Thanks
EDIT 2:
i thought id show my actual script instead, what im doing is searching a table, and im page load i want to hide rows that contain a string. so if exlucde lenght is greater than 0 hide that row...
function searchPagingTable(inputVal, tablename, fixedsearch, exclude) {
var table = $(tablename);
table.find('tr:not(.header)').each(function (index, row) {
var allCells = $(row).find('td');
if (allCells.length > 0) {
var found = false;
allCells.each(function (index, td) {
if (fixedsearch == 1) {
var regExp = new RegExp("^" + inputVal + "$", 'i');
}
else if (exclude.length > 0)
{
var regExp = new RegExp("^(?!" + exclude + ")", "i");
}
else {
var regExp = new RegExp(inputVal, 'i');
}
if (regExp.test($(td).text())) {
found = true;
return false;
}
});
if (found == true) $(row).show().removeClass('exclude'); else $(row).hide().addClass('exclude');
}
});
pa
ginate();
}
That would be
var exclude = "Fred"
var regExp = new RegExp("^(?!.*" + exclude + ")", "i");
This regex matches any string except those that contain Fred. It doesn't actually match any characters in the string, but that's sufficient if you're just looking for a true/false result.
This will also find strings that contain Alfred or Fredo, so if you don't want that, you need to tell the regex only to look for entire words using word boundaries:
var regExp = new RegExp("^(?!.*\\b" + exclude + "\\b)", "i");
You need to make sure that your exclude string only contains ASCII letters/digits (or underscores) for this to work correctly.
You could populate a list of names you wish to match against:
var validNames = ['bob', 'bill'];
Then lowercase each input and match against the list:
if (validNames.indexOf(inputVal.toLowerCase()) != -1) {
// it's a good name
}
For older browsers you have to shim Array.indexOf()
var re = new RegExp('^\\s*Fred\\s*$','i');
if (inputVal.match(re)) {
// Fred has been found
} else {
// Anything has been found
}
So, for example:
//The string to search through
var str = "This is a string /* with some //stuff in here";
//I'm matching three possible things: "here" or "//" or "/*"
var regEx = new RegExp( "(here)|(\\/\\/)|(\\/\\*)", "g" );
//Loop and find them all
while ( match = regEx.exec( str ) )
{
//Which one is matched? The first parenthesis subexpression? The second?
alert( match[ 0 ] );
}
How do i know I matched the "(//)" instead of the "(here)" without running another regex against the returned match?
You can check which group is defined:
var str = "This is a string /* with some //stuff in here";
var regEx = /(here)|(\/\/)|(\/\*)/g;
while(match = regEx.exec(str)){
var i;
for(i = 1; i < 3; i++){
if(match[i] !== undefined)
break;
}
alert("matched group " + i + ": " + match[i]);
}
Running at http://jsfiddle.net/zLD5V/