How to compare two strings within a single line in java script - javascript

I got the String as :-Time in Queue,Item Type, Status,Type,Name, 22days, Document,Idle,Default,test4.
Now I have to compare status and its corresponding values as idle.
How to pick these two words in a single line and compare using java script.

If the structure is fixed, you could, for example, split the string
var result = "-Time in Queue,Item Type, Status,Type,Name, 22days, Document,Idle,Default,test4".split(",")[7] === 'Idle';
But I think you need something else, it is just unclear from the description. Probably if you added some context and described why you need this (why it must be single line, where the data came from, how they are really structured etc.), you could get a better answer.

...is there a line-break there, somewhere?
...you could do something like:
var string = "Time in Queue,Item Type,Status,Type,Name, 22days,Document,Idle,Default,test4",
pieces = string.split(","),
match = pieces[2].trim() === "Status" && pieces[6].trim() === "Idle";
...of course, .trim doesn't work on old browsers, but you can write something similar, easily.
If you really, really want to go golfing, you could do something like:
var string = "Time in Queue,Item Type,Status,Type,Name, 22days,Document,Idle,Default,test4",
reg = /[^,]+,[^,]+,\s*Status\s*,[^,]+,[^,]+,[^,]+,[^,]+,\s*Idle\s*/i;
reg.test(string);
This will tell you if "..., ..., Status, ..., ..., ..., ..., Idle" happens in the string, where "..." is any set of characters which isn't a comma.
If that's not what you mean, then you need to get more specific, here.

Related

Call function saved as string on chosen object

I have something like:
var sFunction = 'my_function("param1", "param2")';
var oMyObject = ...;
And I want to combine it so the result would be equal to:
oMyObject.my_function("param1", "param2");
Would much appreciate any tips.
Remark
As many of you suggested to find a root cause and try not to deal with the problematic input here are some pieces of information about the origins of the "problem".
The sFunction comes from database, hardcoded in one of the columns. It is custom one which should be called on object retrieved basing on other parameters of sFunction's database record.
So being backed up by your comments I will try suggesting changing data model in hope that it is not too late for that. Thank you all for your help.
I am given that as an input, it may come from db or anywhere else. I just have to deal with it in described way.
As Luca noted, you're probably best off solving the problem that brought you to the point of having code in a string that you feel you need to evaluate at runtime. The number of use cases for doing that is very low.
For instance, instead of
sFunction = 'my_function("param1", "param2")';
perhaps you could have
call = {
f: "my_function",
params: ["param1", "param2"]
};
Then it's:
oMyObject[call.f].apply(oMyObject, call.params);
call could even start life as JSON text you parse -- live example:
var json =
'{' +
'"f": "my_function",' +
'"params": ["param1", "param2"]' +
'}';
var call = JSON.parse(json);
var oMyObject = {
my_function: function(p1, p2) {
console.log(p1, p2);
}
};
oMyObject[call.f].apply(oMyObject, call.params);
That's markedly safer than an arbitrary code execution.
You can do this with your sFunction (eval("oMyObject." + sFunction)), but consider:
It lets any arbitrary code in sFunction run.
If User A supplies the code and then you run it on User B's system, you're compromising User B's privacy. (I am not a lawyer, but you could be doing so in a way that violates a country's data protection or privacy laws.)
Now, if you're loading code from a DB and you know that the code in the DB can only be put there by trusted people (for instance, developers on your team, not end users of the system), that's fine, it's largely like running a script file. But there's almost certainly a better way to do it than delivering the code as a string and evaling it.
But if the code comes from "anywhere else", it's not fine; see bullet points above. The setup is fundamentally broken and better options are available. Take that information to your boss, and if necessary to his/her boss, and if necessary his/her boss, until you find someone who can change the requirement.
Here's a string hack that doesn't use eval(), but as I (and others) have said, this is not a good solution. The better solution would be to return the function name and any arguments as a comma delimited string, which would at least make this kind of solution more straight-forward.
var sFunction = 'my_function("param1", "param2")';
// The object would have to already have the function:
var oMyObject = {
my_function: function(x,y){
return x + y;
}
};
// Remove the last ")" and split the remainder into an array at the "("
var funcParts = sFunction.replace(")","").split("(");
// Split the second part (the arguments) into its own array
var funcArgs = funcParts[1].split(",");
// Pass the function name as a string key to the object and then pass the arguments to that
console.log(oMyObject[funcParts[0]](funcArgs[0], funcArgs[1]));
The bigger question is, what ultimately are you trying to accomplish as there is almost always a better approach than this.
To do a dynamic function call you can of course eval as I did in the comments, which is of course a terrible idea. Here is a quick-and-dirty alternative:
const dynamicCallMethod = (obj, s) => {
try {
const fname = s.match(/([$\w]+\(/);
const params = s.match(/("[\w$]+")/g);
return obj[fname](...params);
} catch (e) {
return e;
}
};
Note I still think there's any easier way to do this if you describe the scenario in more detail. The above will fail for any non-ascii characters, for instance.

jQuery Multiple Strings Case and Accent Insensitive

My first post on here. I have a function on a website whereby a randomly generated French phrase is displayed, challenging the reader to translate it into English in a text box. On clicking on a button, the text entered is compared to all the possible answers (there are multiple correct translations for a given phrase). I've looked around for answers on this but nothing seems to suit my situation.
Here's the jQuery:
var correctAnswer = function(){$('#correctmessage').show('fast');$('#errormessage').hide('fast');}
var wrongAnswer = function(){$('#errormessage').show('fast');$('#correctmessage').hide('fast');}
$('#1').find('button').on('click', function(){
var text = $(this).parent().find('.translatefield').val();
var compareText = "I went to the cinema";
var compareText2 = "I have been to the cinema";
if (text == compareText || text == compareText2) {
correctAnswer();
}
else {
wrongAnswer();
}
});
So I wondered if I can put the 'compare' variables into one variable i.e. 'I went to the cinema OR I have been to the cinema OR etc etc' within one variable for tidiness. But mainly I need to know how I can call that variable within the if so that it also accepts the answer without accented characters and regardless of upper or lower case... I hope this is clear! Thanks for any help you can give, this has been irritating me for a while!
As commented by Mark Holland, use arrays for the compare phrases.
If you are using jQuery anyway, you could use jQuery.inArray().
https://api.jquery.com/jQuery.inArray/
var compareText = ['i went to the cinema','i have been to the cinema'];
if ($.inArray(text.toLowerCase(), compareText)) {
... do stuff
}
To ignore the accents, use a solution like this:
String.prototype.removeAccents = function(){
return this
.replace(/[áàãâä]/gi,"a")
.replace(/[éè¨ê]/gi,"e")
.replace(/[íìïî]/gi,"i")
.replace(/[óòöôõ]/gi,"o")
.replace(/[úùüû]/gi, "u")
.replace(/[ç]/gi, "c")
.replace(/[ñ]/gi, "n")
.replace(/[^a-zA-Z0-9]/g," ");
}
Credits to Luan Castro
Perform a find/match with javascript, ignoring special language characters (accents, for example)?
As mentionned by Mark Holland, arrays would answer your first question.
JS arrays
To ignore accents, a quick search gave me this answer:
Replace accents
And to ignore lower/uppercase, a quick search gave me this answer.
Ignore case
How about setting the strings into one array and iterate this array to compare with the answer?

How to make indexOf only match 'hi' as a match and not 'hirandomstuffhere'?

Basically I was playing around with an Steam bot for some time ago, and made it auto-reply when you said things in an array, I.E an 'hello-triggers' array, which would contain things like "hi", "hello" and such. I made so whenever it received an message, it would check for matches using indexOf() and everything worked fine, until I noticed it would notice 'hiasodkaso', or like, 'hidemyass' as an "hi" trigger.
So it would match anything that contained the word even if it was in the middle of a word.
How would I go about making indexOf only notice it if it's the exact word, and not something else in the same word?
I do not have the script that I use but I will make an example that is pretty much like it:
var hiTriggers = ['hi', 'hello', 'yo'];
// here goes the receiving message function and what not, then:
for(var i = 0; i < hiTriggers.length; i++) {
if(message.indexOf(hiTriggers[i]) >= 0) {
bot.sendMessage(SteamID, randomHelloMsg[Math stuff here blabla]); // randomHelloMsg is already defined
}
}
Regex wouldn't be used for this, right? As it is to be used for expressions or whatever. (my English isn't awesome, ikr)
Thanks in advance. If I wasn't clear enough on something, please let me know and I'll edit/formulate it in another way! :)
You can extend prototype:
String.prototype.regexIndexOf = function(regex, startpos) {
var indexOf = this.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}
and do:
var foo = "hia hi hello";
foo.regexIndexOf(/hi\b/);
Or if you don't want to extend the string object:
foo.substr(i).search(/hi\b/);
both examples where taken from the top answers of Is there a version of JavaScript's String.indexOf() that allows for regular expressions?
Regex wouldn't be used for this, right? As it is to be used for expressions or whatever. (my > English isn't awesome, ikr)
Actually, regex is for any old pattern matching. It's absolutely useful for this.
fmsf's answer should work for what you're trying to do, however, in general extending native objects prototypes is frowned upon afik. You can easily break libraries by doing so. I'd avoid it when possible. In this case you could use his regexIndexOf function by itself or in concert with something like:
//takes a word and searches for it using regexIndexOf
function regexIndexWord(word){
return regexIndexOf("/"+word+"\b/");
}
Which would let you search based on your array of words without having to add the special symbols to each one.

javascript regex match not working as expected

I'm trying to do something very simple, but I can't get to work the way I intend. I'm sure it's doing exactly what I'm asking it to do, but I'm failing to understand the syntax.
Part 1:
In the following example, I want to extract the part of the string between geotech and Input.
x = "geotechCITYInput"
x.match(/^geotech(.*)(?:Input|List)$/)
The result:
["geotechCITYInput", "CITY"]
I've been writing regex for many years in perl/python and even javascript, but I've never seen the ?: syntax, which, I think, is what I'm supposed to use here.
Part 2:
The higher level problem I'm trying to solve is more complicated. I have a form with many elements defined as either geotechXXXXInput or geotechXXXXList. I want to create an array of XXXX values, but only if the name ends with Input.
Example form definition:
obj0.name = "geotechCITYInput"
obj1.name = "geotechCITYList"
obj2.name = "geotechSTATEInput"
obj3.name = "geotechSTATEList"
I ultimately want an array like this:
["CITY","STATE"]
I can iterate over the form objects easily with an API call, but I can't figure out how to write the regex to match the ones I want. This is what I have right now, but it doesn't work.
geotechForm.forEachItem(function(name) {
if(name.match(/Input$/)
inputFieldNames.push( name.match(/^geotech(.*)Input$/) );
});
Any suggestions would be greatly appreciated.
You were missing the Input and List suffix in your regex. This will match if the name starts with geotech and ends with either Input or List and it will return an array with the text in the middle as the second item in the array.
geotechForm.forEachItem(function (name) {
var match = name.match(/^geotech(.*)(Input|List)$/);
if (match) {
inputFieldNames.push(match[1]);
}
});

Why is my .data() function returning [ instead of the first value of my array?

I want to pass an array into a jQuery data attribute on the server side and then retrieve it like so:
var stuff = $('div').data('stuff');
alert(stuff[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<div data-stuff="['a','b','c']"></div>
Why does this appear to alert '[' and not 'a' (see JSFiddle link)
JSFiddle Link: http://jsfiddle.net/ktw4v/3/
It's treating your variable as a string, the zeroth element of which is [.
This is happening because your string is not valid JSON, which should use double-quotes as a string delimiter instead of single quotes. You'll then have to use single-quotes to delimit the entire attribute value.
If you fix your quotation marks your original code works (see http://jsfiddle.net/ktw4v/12/)
<div data-stuff='["a","b","c"]'> </div>
var stuff = $('div').data('stuff');
When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.
Declaring it as an attribute means that it is a string.
So stuff[0] would be equivalent to: var myString = "['a','b','c']"; alert(myString[0]);
You need to make it look like this:
<div data-stuff="a,b,c"></div>
var stuff = $('div').data('stuff').split(',');
alert(stuff[0]);
Retraction: jQuery's parsing fails because it didn't meet the rules of parseJSON.
However, I will stand behind my solution. There are aspects of the others that are less than ideal, just as this solution is less than ideal in some ways. All depends on what your paradigms are.
As others have identified the value is treated as string so it is returning "[". Please try this (aaa is the name of the div and I took out the data-stuff):
$(function(){
$.data($("#aaa")[0],"stuff",{"aa":['a','b','c']});
var stuff = $.data($("#aaa")[0],"stuff").aa;
alert(stuff[0]); //returns "a"
});
A different approach is posted at jsfiddle; var stuff = $('div').data('stuff'); stuff is a string with 0th character as '['
Well, var stuff = eval($('div').data('stuff')); should get you an array

Categories