check if substring exist in string - javascript

I want to check if a sub string is included in a string, but the sub string contains a number, this number can change. I used RegExp but it's not working
let url = "http://localhost:8080/api/issue/board/537/sprint";
url.includes('/issue/board/537/sprint'); // true
the value 537 can change
var reg = new RegExp('^[0-9]+$');
url.includes('/issue/board/' + reg +'/sprint'); // false

That's not how you use Regex.
Create an expression:
const reg = new RegExp('/issue/board/[0-9]+/sprint');
And test it against your url:
const url = "http://localhost:8080/api/issue/board/537/sprint";
const matches = url.test(reg); // true

const reg = new RegExp('/issue/board/[0-9]+/sprint');
const url = "http://localhost:8080/api/issue/board/537/sprint";
const matches = url.match(reg);
console.log(matches ? true: false)

var reg = new RegExp('/issue/board/[0-9]+/sprint')

const regex = new RegExp('\/board\/(.*?)\/sprint');
const url = 'http://localhost:8080/api/issue/board/537/sprint';
const test = regex.test(url);
const matches = regex.exec(url);
console.log(test); // true
console.log(matches[1]); //537

const condition = new RegExp('\/issue\/board\/[0-9]+\/sprint').test('http://localhost:8080/api/issue/board/537/sprint'); // true

Easiest way is just to use indexOf. Like so
let url = "http://localhost:8080/api/issue/board/537/sprint",
match = '/issue/board/537/sprint';
if (url.indexOf(match) !== -1) {
// true
} else {
// false
}
The indexOf a string that isn't contained in the string you're checking will always be -1

Related

JavaScript, include string not included with special characters

I'm trying to ignore some string.
The idea is to check if the string to ignore is included in a list of strings separated by commas. When the string to ignore is "/healthCheck' (case 2) works ok, but in case 1, when the string has more special characters, is not working.
Playground: https://jsfiddle.net/pmiranda/pwfLou6e/7/
const URLS_TO_IGNORE="/healthCheck,/socket.io//?EIO,/socket.io, /otherEndpoint"
// Case 1 not working
const endpointToIgnore = '/socket.io//?EIO=4&transport=polling&t=77qQ9HboF54_NtCdAAb';
const ignoreLogger = URLS_TO_IGNORE.includes(endpointToIgnore);
console.log(ignoreLogger); // false
// Case 2 working
const endpointToIgnore2 = '/healthCheck';
const ignoreLogger2 = URLS_TO_IGNORE.includes(endpointToIgnore2);
console.log(ignoreLogger2); // true
// Case 3 working
const endpointToIgnore3 = '/otherEndpoint';
const ignoreLogger3 = URLS_TO_IGNORE.includes(endpointToIgnore2);
console.log(ignoreLogger3); // true
How can Ignore the string: /socket.io ?
I need a way to valid that every string that starts with /socket.io despite what other characters are after, be included in the ignore function.
use the test() method of the regular expression to check if the string matches the pattern that starts with "/socket.io"
const URLS_TO_IGNORE = "/healthCheck,/socket.io//?EIO=4&transport=polling&t=77qQ9HboF54_NtCdAAb,/socket.io, /otherEndpoint";
// Case 1 working
const endpointToIgnore = '/socket.io//?EIO=4&transport=polling&t=OPVH0sr&sid=77qQ9HboF54_NtCdAAb';
const ignoreLogger = URLS_TO_IGNORE.split(",").some(url => /^\/socket\.io.*/.test(url) && endpointToIgnore.includes(url) );
console.log(ignoreLogger); // true
// Case 2 working
const endpointToIgnore2 = '/healthCheck';
const ignoreLogger2 = URLS_TO_IGNORE.includes(endpointToIgnore2);
console.log(ignoreLogger2); // true
// Case 3 working
const endpointToIgnore3 = '/otherEndpoint';
const ignoreLogger3 = URLS_TO_IGNORE.includes(endpointToIgnore2);
console.log(ignoreLogger3); // true
Take a look at startsWith https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith You could split your URLS_TO_IGNORE by commas to get an array and check if the endpointToIgnore starts with any of them
const URLS_TO_IGNORE="/healthCheck,/socket.io//?EIO,/socket.io, /otherEndpoint".split(',')
const endpointToIgnore = '/socket.io//?EIO=4&transport=polling&t=OPVH0sr&sid=77qQ9HboF54_NtCdAAb'
const ignoreLogger = URLS_TO_IGNORE.some((path)=>endpointToIgnore.startsWith(path));
You can make a dummy URL and look at the pathname
const URLS_TO_IGNORE = ["/healthCheck","/socket.io","/otherEndpoint"];
const checkUrl = path => {
const url = new URL(`https://dummyURL.com${path}`);
const pathname = url.pathname;
const ignore = URLS_TO_IGNORE.some(pn => pathname.startsWith(pn))
console.log("PN:",pathname,"\nign",ignore)
return ignore
};
console.log(checkUrl('/socket.io//?EIO=4&transport=polling&t=OPVH0sr&sid=77qQ9HboF54_NtCdAAb'));
console.log(checkUrl('/socket.io/?EIO=4&transport=polling&t=OPVH0sr&sid=77qQ9HboF54_NtCdAAb'));
console.log(checkUrl('/okendpoint'));
console.log(checkUrl('/healthCheck'));
console.log(checkUrl('/otherEndpoint'));
let text = "";
const check_urls = ['/socket.io//?EIO=4&transport=polling&t=OPVH0sr&sid=77qQ9HboF54_NtCdAAb','/healthCheck']
const urs= '/socket.io//?EIO=4&transport=polling&t=OPVH0sr&sid=77qQ9HboF54_NtCdAAb';
check_urls.forEach(ifun);
function ifun(item, index) {
text += index + ": " + item +" == "+ urs.includes(item);
}
console.log(text);

Javascript & regular expression

I have this string
java=10514;js=237;jsp=3995;web=5;xml=42
and I'd like to extract, in separate variables, the value numbers for each language, using javascript and a regular expression that is, for the "java" case, the follow
(?<=java=).*?(?=;|$)
I've tried this code
var myString = "java=10514;js=237;jsp=3995;web=5;xml=42";
var regexp_java = new RegExp('(?<=java=).*?(?=;|$)', 'g');
var ncloc_java = sonar_myString.match(regexp_java);
var regexp_js = new RegExp('(?<=js=).*?(?=;|$)', 'g');
var ncloc_js = sonar_myString.match(regexp_js);
var regexp_jsp = new RegExp('(?<=jsp=).*?(?=;|$)', 'g');
var ncloc_jsp = sonar_myString.match(regexp_jsp);
var regexp_web = new RegExp('(?<=web=).*?(?=;|$)', 'g');
var ncloc_web = sonar_myString.match(regexp_web);
var regexp_jsp = new RegExp('(?<=jsp=).*?(?=;|$)', 'g');
var ncloc_jsp = sonar_myString.match(regexp_jsp);
but it doesn't work.
Any suggestion will be appreciated and thank you in advance
I believe that you are using the wrong data structure here. Rather than trying to use individual variables for each language, you can instead use a hashmap. First split to the string on semicolon, and then stream that to get each language and value.
var input = "java=10514;js=237;jsp=3995;web=5;xml=42";
var map = {};
input.split(";").forEach(x => map[x.split("=")[0]] = x.split("=")[1]);
console.log(map);
Does it really need to be done with Regex? Anyways I'm providing you with 2 solutions.
const string = "java=10514;js=237;jsp=3995;web=5;xml=42";
let result1 = string.split(';').reduce((acc, curr) => {
let [key, value] = curr.split('=');
acc[key] = value;
return acc;
}, {});
console.log(result1);
let result2 = {};
let regex = /([a-z]+)\s*=\s*(\d+)/g;
let check;
while (check= regex.exec(string)) {
result2[check[1]] = check[2];
}
console.log(result2);
You don't have to create separate patterns and variables, Instead you can use 2 capture groups and then create an object with keys and values (assuming there are no duplicate keys)
\b(java|jsp?|web|xml)=([^;\s]+)
Explanation
\b A word boundary
(java|jsp?|web|xml) Match one of the alternatives
= Match literally
([^;\s]+) Capture group 2, match 1+ chars other than a whitespace char or ;
See a regex demo.
const myString = "java=10514;js=237;jsp=3995;web=5;xml=42";
const regex = /\b(java|jsp?|web|xml)=([^;\s]+)/g;
const kv = Object.fromEntries(
Array.from(
myString.matchAll(regex), m => [m[1], m[2]]
)
)
console.log(kv)
console.log(kv.java);

Check if a string contains a specific word only once

I am trying to check if a string contains a specific word only once.
Here is my attempt, but it's not working:
const test = "hello this is a new string hello";
// if hello contains only once then true otherwise false;
// here is my try but
let containshello = test.includes("hello");
console.log(containshello);
Here's an approach using filter
const containsWordOnce = (str, searchKey) => {
return str.split(' ').filter((word) => word === searchKey).length === 1;
};
const test = "hello this is a new string hello";
console.log(containsWordOnce(test, "hello"));
Use 'regex match' to get the occurrence of a substring in a string.
const test = "hello this is a new string hello";
console.log(test.match(/hello/gi)?.length); // 2 : 'hello' two times
console.log(test.match(/new/gi)?.length); // 1 : 'new' one time
console.log(test.match(/test/gi)?.length); // undefined : 'test' doesn't exist in string.
I have used 'g' for Global checking and 'i' for ignoring the case.
If you want to create 'Regex' object create like this:
const test = "hello this is a new string hello";
const regx = new RegExp('hello', 'gi') // /hello/gi
console.log(test.match(regex)?.length);
const test = "hello this is a new string hello";
const findString = "hello"
console.log(test.split(findString).length-1 === 1)
I would just use a regular expression and use the match method on the string you would like to search using the "i" and "g" flag. Below is an example function although there are most likely better ways.
function containsWordOnce(string, word) {
const re = new RegExp(word, 'ig');
const matches = string.match(re);
return matches.length === 1;
}
Just plug in your string and word your trying to find.

How to match identical strings in Javascript?

Take these two urls:
const url1 = '/user/{username}/edit'
const url2 = '/user/harry/edit'
Is there a solution to match these two urls and return true as they are similar?
I tried the following and should be the worst solution:
const url1 = '/user/{username}/edit'
const url2 = '/user/harry/edit'
const split1 = url1.split('/')
const split2 = url2.split('/')
let matchCount = 0
let notMatchedCount = 0
split1.map(x => {
if(x === split2[x]) {
matchCount++
} else {
notMatchedCount++
}
})
if(matchCount > notMatchedCount) {
console.log('Match Found')
} else {
console.log('Match not found')
}
EDIT
Solution was to use PathToRegExp package! Thanks to #ChiragRavindra!
You could use a regex to test the url
\/user\/ matching /user/
\w+ matching 1 or more word characters ([a-zA-Z0-9_]+)
\/edit matching /edit
const url1 = '/user/{username}/edit';
const urlCorrect = '/user/harry/edit';
const urlWrong = '/users/harry/edit';
//generate a regex string by escaping the slashes and changing word between curly brackets with {\w+}
var regexString = url1.replace(/\{\w+\}/g, '\\w+').replace(/\//g, '\\/');
console.log('generating regex: ' + regexString);
var regex = new RegExp(regexString);
//test using the generated regex
console.log(regex.test(urlCorrect));
console.log(regex.test(urlWrong));
I would suggest you to look inside this library
NPM - String similarity library
Library simply returns the probability of comparing two strings if they're similar.
Then it's all on you to set up the threshold from how many percentages you assume that they're the same.

remove chars in String javascript Regex

I have a chain like this of get page
file.php?Valor1=one&Valor2=two&Valor3=three
I would like to be able to delete the get request parameter with only having the value of it. for example , remove two
Result
file.php?Valor1=one&Valor3=three
Try with
stringvalue.replace(new RegExp(value+"[(&||\s)]"),'');
Here's a regular expression that matches an ampersand (&), followed by a series of characters that are not equals signs ([^=]+), an equals sign (=), the literal value two and either the next ampersand or the end of line (&|$):
/&[^=]+=two(&|$)/
let input = 'file.php?&Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(/&[^=]+=two/, '');
console.log(output);
If you're getting the value to be removed from a variable:
let two = 'two';
let re = RegExp('&[^=]+=' + two + '(&|$)');
let input = 'file.php?&Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(re, '');
console.log(output);
In this case, you need to make sure that your variable value does not contain any characters that have special meaning in regular expressions. If that's the case, you need to properly escape them.
Update
To address the input string in the updated question (no ampersand before first parameter):
let one = 'one';
let re = RegExp('([?&])[^=]+=' + one + '(&?|$)');
let input = 'file.php?Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(re, '$1');
console.log(output);
You can use RegExp constructor, RegExp, template literal &[a-zA-Z]+\\d+=(?=${remove})${remove}) to match "&" followed by "a-z", "A-Z", followed by one or more digits followed by "", followed by matching value to pass to .replace()
var str = "file.php?&Valor1=one&Valor2=two&Valor3=three";
var re = function(not) {
return new RegExp(`&[a-zA-Z]+\\d+=(?=${not})${not}`)
}
var remove = "two";
var res = str.replace(re(remove), "");
console.log(res);
var remove = "one";
var res = str.replace(re(remove), "");
console.log(res);
var remove = "three";
var res = str.replace(re(remove), "");
console.log(res);
I think a much cleaner solution would be to use the URLSearchParams api
var paramsString = "Valor1=one&Valor2=two&Valor3=three"
var searchParams = new URLSearchParams(paramsString);
//Iterate the search parameters.
//Each element will be [key, value]
for (let p of searchParams) {
if (p[1] == "two") {
searchParams.delete(p[0]);
}
}
console.log(searchParams.toString()); //Valor1=one&Valor3=three

Categories