Javascript string trimming: Url and file path - javascript

Here comes javascript noob again.
What I would like to do. 1:
// I will have many URLs as input
// I want to check if URL NOT end with slash
// if not then trim string after slash
var given_URL = "http://www.test.com/test"
var trimmed_URL = "http://www.test.com/"
What I would like to do. 2:
// I will have many file paths
// I would like to check if the path starts with unwanted dot OR slash
// If so, I would like to trim it
var given_path_1 = "./folder/filename.xxx"
var given_path_2 = "/folder/filename.xxx"
var given_path_3 = ".folder/filename.xxx"
var trimmed_path = "folder/filename.xxx"
I would like to know how to achieve these.
Thanks in advance

For your first question, you should use the lastIndexOf method.
For example:
var index = given_URL.lastIndexOf("/");
Check if index === given_URL.length - 1 is true. If it is, you can use the slice method to cut your url.
For example:
var newUrl = given_URL.slice(0,index);
For your second question, you can check if given_URL[0] === "." or given_URL[0] === "/". If this is true, then use the slice method to slice it.
For example:
var newUrl = given_URL.slice(1, given_URL.length - 1);

You should try to use replace() using some regex:
//replace all "/*" at the end with "/"
given_URL.replace(/\/\w+$/,'/');
//replace all non letters at the start with ""
given_path_2.replace(/^\W+/,'');

To trim until the last forward slash /, you could find the last occurrence of it and check if it the last letter in the string. If it is, you take the string until after that last occurrence.
To remove an optional dot (\.?), followed by an optional forward slash (\/?) from the start (^) of a string, you could do a replace with a regex of ^\.?\/?.
function trimToLastForwardslash(input) {
var lastBackSlash = input.lastIndexOf('/');
return lastBackSlash != -1 && lastBackSlash != input.length - 1 ? input.substring(0, lastBackSlash + 1) : input;
}
function trimFirstDotOrForwardSlash(input) {
return input.replace(/^\.?\/?/, '');
}
var path = "http://www.test.com/test";
console.log(path + ' => trim last slash => ' + trimToLastForwardslash(path));
path = "http://www.test.com/test/";
console.log(path + ' => trim last slash => ' + trimToLastForwardslash(path));
path = "./folder/filename.xxx";
console.log(path + ' => trim first dot or slash => ' + trimFirstDotOrForwardSlash(path));
path = "/folder/filename.xxx";
console.log(path + ' => trim first dot or slash => ' + trimFirstDotOrForwardSlash(path));
path = ".folder/filename.xxx";
console.log(path + ' => trim first dot or slash => ' + trimFirstDotOrForwardSlash(path));

Related

Replace all “?” by “&” except first

I’d would to replace all “?” by “&” except the first one by javascript. I found some regular expressions but they didn’t work.
I have something like:
home/?a=1
home/?a=1?b=2
home/?a=1?b=2?c=3
And I would like:
home/?a=1
home/?a=1&b=2
home/?a=1&b=2&c=3
Someone know how to I can do it?
Thanks!
I don't think it's possible with regex but you can split the string and then join it back together, manually replacing the first occurance:
var split = 'home/?a=1?b=2'.split('?'); // [ 'home/', 'a=1', 'b=2' ]
var replaced = split[0] + '?' + split.slice(1).join('&') // 'home/?a=1&b=2'
console.log(replaced);
You could match from the start of the string not a question mark using a negated character class [^?]+ followed by matching a question mark and capture that in the first capturing group. In the second capturing group capture the rest of the string.
Use replace and pass a function as the second parameter where you return the first capturing group followed by the second capturing group where all the question marks are replaced by &
let strings = [
"home/?a=1",
"home/?a=1?b=2",
"home/?a=1?b=2?c=3"
];
strings.forEach((str) => {
let result = str.replace(/(^[^?]+\?)(.*)/, function(match, group1, group2) {
return group1 + group2.replace(/\?/g, '&')
});
console.log(result);
});
You can split it by "?" and then rewrap the array:
var string = "home/?a=1?b=2";
var str = string.split('?');
var new = str[0] + '?'; // text before first '?' and first '?'
for( var x = 1; x < str.length; x++ ) {
new = new + str[x];
if( x != ( str.length - 1 ) ) new = new + '&'; //to avoid place a '&' after the string
}
You can use /([^\/])\?/ as pattern in regex that match any ? character that isn't after / character.
var str = str.replace(/([^\/])\?/g, "$1&");
var str = "home/?a=1\nhome/?a=1?b=2\nhome/?a=1?b=2?c=3\n".replace(/([^\/])\?/g, "$1&");
console.log(str);

Hyphen for after 2nd character

I would like to write a simple function to mask an input with a date like 12-2018 (MM-YYYY) and used a regex like below, but its return the number with a slash for every 2 digits. But I am looking only slash with after first 2 digits only. I have searched for a lot and got below hint only.
("122018").match(new RegExp('.{1,2}', 'g')).join("-")
("122018").match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
Your regex should simply specify the exact number of characters in the curly braces. Refer to the capture groups when replacing.
Use '-?' or '.?' to allow an optional (dash or any) delimiter. Or take it out if you do not want to allow delimiters.
You might want to allow for optional spaces around your input too...
let inputValues = ['122018', '12-2018', '2018']
let res = rx = /(\d{2})(\d{4})/
//let res = rx = /(\d{2})-?(\d{4})/
inputValues.forEach(inputValue => {
let m = res.exec(inputValue)
if (m) {
console.warn('good input: ' + inputValue)
//console.log(m[1] + '/' + m[2])
} else {
console.warn('bad input: ' + inputValue)
}
})
date = '122018';
arr = date.match(/^(..)(.+)$/);
res = [arr[1],arr[2]].join('-');
console.log(res);

Turning a string from PascalCase to param-case: remove extra dash at the beginning

I'm trying to turn a string from PascalCase to param-case:
'HelloWorld'.replace(/([A-Z])/g, (str) => { return '-' + str.toLowerCase() })
"-hello-world"
As you can see, I'm almos there ... I just have to remove the - at the beginning of the string. How to do that?
In your Code, for removing the first word, you just need to ignore the first character by using substring(1) off your rest of the output
var output = 'HelloWorld'.replace(/([A-Z])/g, (str) => { return '-' + str.toLowerCase() }).substring(1);
or alternatively you can convert from pascalcase to camelcase by doing this
var output = 'HelloWorld'.split(/(?=[A-Z])/g).map(function(value){ return value.charAt(0).toLowerCase()+ value.substring(1)}).join("-");
DEMO Below
var output = 'HelloWorld'.split(/(?=[A-Z])/g).map(function(value){ return value.charAt(0).toLowerCase()+ value.substring(1)}).join("-");
document.body.innerHTML += output;
You can use follow code:
var name = "HelloWorld";
var paramCaseName = name.replace(/([A-Z]+(.))/g, function(_, separator, letter, offset) {
return (offset ? "-" + separator : separator).toLowerCase();
});
console.log(paramCaseName);
Based on angular source code.

How to replace css('background-image')

I want to replace css('background-image') path.
The problem:
for the same variable oldBgImg = this.element.css('background-image')
FireFox returns -
"url("http://mySite/images/file1.png")"
but Chrome returns it without the quotes:
"url(http://mySite/images/file1.png)"
Here is the solution I use. can you please help me make it simpler?
var oldBgImg = this.element.css('background-image');
// => FF: "url("http://mySite/images/file1.png")"
// Chrome: "url(http://mySite/images/file1.png)"
// According to http://www.w3.org/TR/CSS2/syndata.html#value-def-uri :
// quotes are optional, so Chrome does not use them, but FF does . . .
var n1 = oldBgImg.lastIndexOf("("); n1 += 1; // now points to the char after the "("
var n2 = oldBgImg.lastIndexOf(")"); n2 -= 1; // now points to the char before the ")"
var c1 = oldBgImg.substring(n1, n1 + 1); // test the first Char after the "("
var c2 = oldBgImg.substring(n2, n2 + 1); // test the first Char after the "("
if ( (c1 == "\"") || (c1 == "\'") ) { n1 += 1; }
if ( (c2 == "\"") || (c2 == "\'") ) { n2 -= 1; }
var oldBgImgPath = oldBgImg.substring(n1, n2 + 1); // [ (" ] .. [ ") ]
var n = oldBgImgPath.lastIndexOf("/");
var newBgImgPath = oldBgImgPath.substring(0, n + 1) + "file2.gif";
// if needed, should also add :
// var path = encodeURI(newBgImgPath);
this.element.css('background-image', 'url(' + newBgImgPath + ')');
Notes:
According to http://www.w3.org/TR/CSS2/syndata.html#value-def-uri
one can use single quote or double-quote or no quote sign
I am looking for a general solution, also for relative path (without "http" or with "file") , I just want to replace the fileName within the URL.
Here's an example of how to do it with regular expressions. - live demo
The expression:
("?)(http:.*?)\1\)
The match
url = 'url("http://mySite/images/file1.png")'.match(/("?)(http:.*?)\1\)/)[2];
You can then reconstruct your property.
$(this).css( 'background-image', 'url("' + url + "')" );
This should work on all browsers.
I did it with regular expressions. I use this code:
var re = /url\(['"]?(.+?)[^\/]+['"]?\)/;
var regs = re.exec(oldBgImg);
var newBgImgPath = regs[1] + "file2.png";
JSFiddle
I'll explain the RE.
It starts with a /, this will indicate it's a RE.
Then there's url\(. It matches the text url(. ( is escaped because it is a reserved character.
Then there is ['"]?. ['"] matches ' or " and the ? makes it optional.
A ( starts a RE group, that can be referred to.
In .+? . matches all charaters except a newline. A + tells that there must be at least 1 of them, or more. Finally, a ? makes the + non-greedy, so it matches as little characters as possible but still tries to match the whole RE.
A ) ends the group.
[^\/] matches any non-/ character. Then there's a + again. It has no ? after it, because we want to match as many non-/ characters (the file name) from the end as we can.
Finally, another optional quote, an escaped ) for the closing bracket in url(...) and a / to end the RE.
Now re.exec(oldBgImg) returns an array with the first element being the whole matched string and the next elements being the matched RE groups (created by () brackets). Then I can just take regs[1], which is the first matched group and contains the pathname.
You could replace the quotes in oldBgImg with nothing like this.
oldBgImg = oldBgImg.replace(/\"/g, "");
That way the URL is always the same no matter what browser retrieved it.

Replace ID in a URL between two markers

I have a url which looks like this:
I want to replace: 1034749-184e-3467-87e0-d7546df59896 with another ID, is there any regex or similar replace method which will allow me to replace the ID using JavaScript between the 'image/' and '?' characters?
You could make this approximation expression:
/[0-9a-z]+(?:-[0-9a-z]+){4}/i
Match a bunch of hexadecimals, followed by 4 sections, each starting with a dash followed by a bunch of hexadecimals.
> var s = 'http://url/images/1034749-184e-3467-87e0-d7546df59896?w=600&r=22036';
> console.log(s.replace(/[0-9a-z]+(?:-[0-9a-z]+){4}/i, 'something-else'));
http://url/images/something-else?w=600&r=22036
/images\/[^?]+/ would match, but it would replace images/ as well.
Fortunately you can pass a callback to .replace:
url.replace(/(images\/)[^?]+/, function($match, $1) {
// results in "images/<some-ID>"
return $1 + theNewId;
});
If you have a reference to the DOM element anyway, you can also just replace the last step of the path:
element.pathname =
element.pathname.substring(0, element.pathname.lastIndexOf('/') + 1) + newId;
Yes, just do this:
var url = document.getElementById("yoururlid").src;
url = url.split("/");
var newUrl = url[0] + url[1] + url[2] + url[3] + newURLID;
Why not just do this:
document.getElementById("yoururlid").src="http://url/images/" + newId + "?w=600&r=22036";

Categories

Resources