I have these strings which are addresses of files and folder:
../../../folder1/sub1/sub12/
../../../folder1/
../../../another-folder/
I want to compare them using javascript - possibily jquery - to see if for example string 1 have a part egual to string 2 but something more saying that string 1 is child of string 2.
How can i do this?
you could try something like the following
var path1 = "../../../folder1/";
var path2 = "../../../folder1/sub1/sub12/";
if (path2.indexOf(path1) != -1){
//path2 is a sub of path 1
}
In case your string can contain also absolute paths or paths containing .. not only at the beginning I would recommend checking if .indexOf return 0 instead of anything that is not -1.
It can help with cases like.
var path1 = "/rootFolder/";
var path2 = "../folder/rootFolder/";
if (path2.indexOf(path1) === 0) {
console.log("You want this"); // won't get executed => good
}
if (path2.indexOf(path1) !=-1) {
console.log("You don't want this"); // will get executed => bad
}
if(string1.indexOf(string2) != -1){
//string2 is present in string1
}
else{
//string2 is not present in string1
}
You can use the indexOf method to find whether one string is a part of another string.
From w3schools documentation:
The indexOf() method returns the position of the first occurrence of a
specified value in a string.
This method returns -1 if the value to search for never occurs.
var test = "../folder/subfolder1";
var test2 = "../folder";
if (test.indexOf(test2) !=-1) {
alert(test + " is a subfolder of " + test2);
}
Related
I have a url with format like this:
http://www.test.com/document/navigate/{{project_id}}/{{note_id}}
the value within {{}} will be filled with integer, like this for example
http://www.test.com/document/navigate/1/3
http://www.test.com/document/navigate/7/2
http://www.test.com/document/navigate/3
the value for note_id in the url is not mandatory, but i need to retrieve both for the project_id and note_id. how can i achieve that?
You can use a regular expression: http[s]?:\/\/www.test.com\/document\/navigate\/([\d]+)[\/]?([\d]+)?[\/]?.
Essentially it is laying out the protocol, hostname/domain, and the part of the path that we know. Then there are two capturing groups - the project ID and the note ID (optional).
You could use it like so:
const url = 'http://www.test.com/document/navigate/1/3';
const parts = url.match(/http[s]?:\/\/www.test.com\/document\/navigate\/([\d]+)[\/]?([\d]+)?/);
console.log(parts[0]); // "http://www.test.com/document/navigate/1/3" <- full match
console.log(parts[1]); // "1" <- first group
console.log(parts[2]); // "3" <- second group, which will be undefined if left off
Note: this may not be a foolproof answer. I recommend trying out many other potential variations. Also be aware that this returns strings, so you may have to parseInt() or something if you want real numbers.
Here is a Regexr showing you how this works (this is how I mess around until I get it right).
One way you can make use of the part navigate/ like the following way:
var url1 = 'http://www.test.com/document/navigate/1/3';
var url2 = 'http://www.test.com/document/navigate/7/2';
var url3 = 'http://www.test.com/document/navigate/3';
function getValue(url){
var arr = url.match(/navigate\/([^ ]*)/);
arr = arr[arr.length - 1].split('/');
if(arr.length == 1)
return { project_id: +arr[0] };
else if(arr.length == 2)
return { project_id: +arr[0], note_id: +arr[1] };
else
return 'invalid';
}
console.log(getValue(url1));
console.log(getValue(url2));
console.log(getValue(url3));
World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax
Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);
I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.
I'm working on my final project of the Winter 2017 quarter to demonstrate how to use Regular Expressions in both C# and JavaScript code behind pages. I've got the C# version of my demonstration program done, but the JavaScript version is making me pull what little hair I have left on my head out (no small achievement since I got a fresh buzz cut this morning!). The problem involves not getting any output after applying a Regular Expression in a While loop to get each instance of the expression and printing it out.
On my HTML page I have an input textarea, seven radio buttons, an output textarea, and two buttons underneath (one button is to move the output text to the input area to perform multiple iterations of applying expressions, and the other button to clear all textareas for starting from scratch). Each radio button links to a function that applies a regular expression to the text in the input area. Five of my seven functions work; the sixth is the one I can't figure out, and the seventh is essentially the same but with a slightly different RegEx pattern, so if I fix the sixth function, the seventh function will be a snap.
(I tried to insert/upload a JPG of the front end, but the photo upload doesn't seem to be working. Hopefully you get the drift of what I've set up.)
Here are my problem children from my JS code behind:
// RegEx_Demo_JS.js - code behind for RegEx_Demo_JS
var inputString; // Global variable for the input from the input text box.
var pattern; // Global variable for the regular expression.
var result; // Global variable for the result of applying the regular expression to the user input.
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder()
{
var strings = [];
this.append = function (string)
{
string = verify(string);
if (string.length > 0) strings[strings.length] = string;
}
this.appendLine = function (string)
{
string = verify(string);
if (this.isEmpty())
{
if (string.length > 0) strings[strings.length] = string;
else return;
}
else strings[strings.length] = string.length > 0 ? "\r\n" + string : "\r\n";
}
this.clear = function () { strings = []; };
this.isEmpty = function () { return strings.length == 0; };
this.toString = function () { return strings.join(""); };
var verify = function (string)
{
if (!defined(string)) return "";
if (getType(string) != getType(new String())) return String(string);
return string;
}
var defined = function (el)
{
// Changed per Ryan O'Hara's comment:
return el != null && typeof(el) != "undefined";
}
var getType = function (instance)
{
if (!defined(instance.constructor)) throw Error("Unexpected object type");
var type = String(instance.constructor).match(/function\s+(\w+)/);
return defined(type) ? type[1] : "undefined";
}
}
Within the code of the second radio button (which will be the seventh and last function to complete), I tested the ScriptBuilder with data in a local variable, and it ran successfully and produced output into the output textarea. But I get no output from this next function that invokes a While loop:
function RegEx_Match_TheOnly_AllInstances()
{
inputString = document.getElementById("txtUserInput").value;
pattern = /(\s+the\s+)/ig; // Using an Flag (/i) to select either lowercase or uppercase version. Finds first occurrence either as a standalone word or inside a word.
//result = pattern.exec(inputString); // Finds the first index location
var arrResult; // Array for the results of the search.
var sb = getStringBuilder(); // Variable to hold iterations of the result and the text
while ((arrResult = pattern.exec(inputString)) !==null)
{
sb.appendLine = "Match: " + arrResult[0] ;
}
document.getElementById("txtRegExOutput").value = sb.toString();
/* Original code from C# version:
// string pattern = #"\s+(?i)the\s+"; // Same as above, but using Option construct for case insensitive search.
string pattern = #"(^|\s+)(?i)the(\W|\s+)";
MatchCollection matches = Regex.Matches(userTextInput, pattern);
StringBuilder outputString = new StringBuilder();
foreach (Match match in matches)
{
string outputRegExs = "Match: " + "\"" + match.Value + "\"" + " at index [" + match.Index + ","
+ (match.Index + match.Length) + "]" + "\n";
outputString.Append(outputRegExs);
}
txtRegExOutput.Text = outputString.ToString();
*/
} // End RegEx_Match_The_AllInstances
I left the commented code in to show what I had used in the C# code behind version to illustrate what I'm trying to accomplish.
The test input/string I used for this function is:
Don’t go there. If you want to be the Man, you have to beat The Man.
That should return two hits. Ideally, I want it to show the word that it found and the index where it found the word, but at this point I'd be happy to just get some output showing every instance it found, and then build on that with the index and possibly the lastIndex.
So, is my problem in my While loop, the way I'm applying the StringBuilder, or a combination of the two? I know the StringBuilder code works, at least when not being used in a loop and using some test data from the site I found that code. And the code for simply finding the first instance of "the" as a standalone or inside another word does work and returns output, but that doesn't use a loop.
I've looked through Stack Overflow and several other JavaScript websites for inspiration, but nothing I've tried so far has worked. I appreciate any help anyone can provide! (If you need me to post any other code, please advise and I'll be happy to oblige.)
Aanval op Vlemis (499|453) C44
This is what the string looks like. Though it's actually like this: "Aanval op variable (variable) variable
What I want to do is 1: get the coordinates (I already have this), 2 get Vlemis (first variable), get C44 (third variable) and check to see if the string is of this type.
My code:
$("#commands_table tr.nowrap").each(function(){
var text = $(this).find("input[id*='editInput']").val();
var attackername= text.match(/(?=op)[\s|\w]*(?=\()/);
var coordinates = text.match(/\(\d{1,3}\|\d{1,3}\)/);
});
Coordinates works, attackername however doesn't.
Html:
<span id="labelText[6]">Aanval op Vlemis (499|453) C44</span>
You should use one regex to take everything :
var parts = text.match(/(\w+)\s*\((\d+)\|(\d+)\)\s*(\w+)/).slice(1);
This builds
["Vlemis", "499", "453", "C44"]
If you're not sure the string is valid, test like this :
var parts = text.match(/(\w+)\s*\((\d+)\|(\d+)\)\s*(\w+)/);
if (parts) {
parts = parts.slice(1);
// do things with parts
} else {
// no match, yell at the user
}
I am working with images, they all have their sizes mentioned in their name tag.
http://mysite.com/audio/display%20image/130x130%20jpeg/5755285.jpg
I am getting those is an array of strings. I need to check if the string contains the size
130x130 in it. How can it be done?
var str = 'http://mysite.com/audio/display%20image/130x130%20jpeg/5755285.jpg';
var search = '130x130';
str.indexOf(search);
If it returns anything but -1 the string has been found:
if (str.indexOf(search) > -1) {
// Your image contains 130x130
} else {
// Your image does not contains 130x130
}