remove chars in String javascript Regex - javascript

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

Related

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);

Regex matching dates in a string in Javascript

Following up from this thread, im trying to make this work
JavaScript regular expression to match X digits only
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate this into 1 array?
However it doesn't look like this is returning the desired results
I'm new to regular expression. What am I doing wrong?
this return an array of matches
result = string.match(re)
This is a function to parse the string encoding those two year values and return the inner years as items of an array:
let o = parseYearsInterval('2016-2022');
console.log(o);
function parseYearsInterval(encodedValue){
var myregexp = /(\d{4})-(\d{4})/;
var match = myregexp.exec(encodedValue);
if (match != null) {
let d1 = match[1];
let d2 = match[2];
//return `[${d1}, ${d2}]`;
let result = [];
result.push(d1);
result.push(d2);
return result;
} else {
return "not valid input";
}
}
I think there are better ways to do that like splitting the string against the "-" separator and return that value as is like:
console.log ( "2016-2022".split('-') )
Just do a split if you know that only years are in the string and the strucutre isn't changing:
let arr = str.split("-");
Question
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate
this into 1 array?
Solution
You may simply flat the result of matchAll.
let string = '2016-2022'
let re = /\d{4}/g
console.log([...string.matchAll(re)].flat())
Alternative
If your structure is given like "yyyy-yyyy-yyyy" you might consider a simple split
console.log('2016-2022'.split('-'))
var str = '2016-2022';
var result = [];
str.replace(/\d{4}/g, function(match, i, original) {
result.push(match);
return '';
});
console.log(result);
I also wanted to mention, that matchAll does basicly nothing else then an while exec, that's why you get 2 arrays, you can do it by yourself in a while loop and just save back what you need
var result = [];
var matches;
var regexp = /\d{4}/g;
while (matches = regexp.exec('2016-2022')) result.push(matches[0]);
console.log(result);

String cutting with Javascript

I have a string like "home/back/step" new string must be like "home/back".
In other words, I have to remove the last word with '/'. Initial string always has a different length, but the format is the same "word1/word2/word3/word4/word5...."
var x = "home/back/step";
var splitted = x.split("/");
splitted.pop();
var str = splitted.join("/");
console.log(str);
Take the string and split using ("/"), then remove the last element of array and re-join with ("/")
Use substr and remove everything after the last /
let str = "home/back/step";
let result = str.substr(0, str.lastIndexOf("/"));
console.log(result);
You could use arrays to remove the last word
const text = 'home/back/step';
const removeLastWord = s =>{
let a = s.split('/');
a.pop();
return a.join('/');
}
console.log(removeLastWord(text));
Seems I got a solution
var s = "your/string/fft";
var withoutLastChunk = s.slice(0, s.lastIndexOf("/"));
console.log(withoutLastChunk)
You can turn a string in javascript into an array of values using the split() function. (pass it the value you want to split on)
var inputString = 'home/back/step'
var arrayOfValues = inputString.split('/');
Once you have an array, you can remove the final value using pop()
arrayOfValues.pop()
You can convert an array back to a string with the join function (pass it the character to place in between your values)
return arrayOfValues.join('/')
The final function would look like:
function cutString(inputString) {
var arrayOfValues = inputString.split('/')
arrayOfValues.pop()
return arrayOfValues.join('/')
}
console.log(cutString('home/back/step'))
You can split the string on the '/', remove the last element with pop() and then join again the elements with '/'.
Something like:
str.split('/');
str.pop();
str.join('/');
Where str is the variable with your text.

Manipulate input string while doing a regex search

trying to find every match in a string and process it with a custom function and replace it in the string. When I set text = to the new string though, it never changes, and in the end remains the unchanged.
function submit () {
var searchTerm = document.querySelector('#search-term').value;
var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\d', 'g');
var match, matches = [];
//search for replacements
while ((match = regex.exec(text)) != null) {
var beforeMatch = output.substring(0, match.index);
var afterMatch = output.substring(match.index + match[0].length, text.length);
text = beforeMatch + replaceFunction(match[0]) + afterMatch;
console.log(text);
}
console.log('result', text);
}
function replaceFunction (input) {
return input * 2;
}
You can achieve same result with far less code using replace() and its function's callback that takes match as parameter.
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
text = text.replace(/\d+/g, function(match){
return parseInt(match) * 2;
})
console.log(text)
First of all, you need to use \\ for escape sequence if you are using RegExp constructor. Alternatively you can use the RegExp literal as shown below. Moreover you are using only \d which is going to match a single digit. Instead you should be using \d+ that will match the complete number.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
When using the constructor function, the normal string escape rules
(preceding special characters with \ when included in a string) are
necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp('\\w+');
Then you are trying to manipulate the string using a loop. Instead simply use replace function as shown below.
function submit () {
// var searchTerm = document.querySelector('#search-term').value;
// var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\\d+', 'g'); // <<<<<< RegExp constructor
// OR
regex = /\d+/g; // <<<<<<< RegExp literal
var match, matches = [];
console.log(text);
output = text.replace(regex, replaceFunction);
console.log('result', output);
}
function replaceFunction (input) {
return parseInt(input) * 2;
}
submit();
Disclaimer: Using RegExp for manipulating HTML elements and attributes is not a good idea and you may end up in unexpected issues if its not used carefully. Use it at your own risk.

How can I loop through string and replace all periods except the last one?

Let's say I have a string like this:
var test = my.long.file.name.zip
I am getting the total number of periods in this string with javascript like so:
var dots = (test.match(/\./g) || []).length;
I would then like to replace all of the periods in the string with underscores if there is more than one period in the string.
if(dots>"1"){
var newname = test.replace(/\./g, "_");
console.log(newname);
}
The problem is that this is replacing all of the periods. I would like to keep the last on intact. So what I would like the newname variable to read as would be:
my_long_file_name.zip
My guess is that I should use $.each() somehow to iterate over all except the last one to change the name. How should I do this?
You dont necessarily need a loop, you could do it with a more complex regex, which uses a positive lookahead
The regex /\.(?=.*\.)/g finds periods, but only where there is a subsequent period somewhere further along, which means the last one is not matched.
window.onload = function(){
var input = "my.long.file.name.zip"
var result = input.replace(/\.(?=.*\.)/g,'_')
alert(result);
}
Consider splitting the string on '.', then re-joining all but the last with '_':
var test = "my.long.file.name.zip";
parts = test.split('.');
var plen = parts.length;
if (plen > 1) {
test = parts.slice(0, plen - 1).join('_') +
"." +
parts[plen - 1];
}
console.log(test);
a lookahead group in regex will work:
var test = 'my.long.file.name.zip';
var result = test.replace(/\.(?=[^.]*\.)/g, '_');
alert(result);
this matches a dot followed by ('anything but dot' and another dot), replacing only what is outside the group
var test = 'my.long.file.name.zip';
var last_index = test.lastIndexOf('.');
var newname = test;
if (-1 !== last_index) {
newname = test.replace(/\./g, '_');
newname = newname.substring(0, last_index).concat('.', newname.substring(last_index + 1));
}
console.log(newname);

Categories