Rewrite Javascript path String - javascript

In Javascript, I have a string for a path that looks like:
/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4
The prefix may or may not be there for each level. I need to create a new string which eliminates the prefix on each folder level, something like:
/Level1/Level2/Level3/Level4
OK. I've done something like the following, but I think perhaps with regex it could be made more compact. How could I do that?
var aa = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4"
var bb = aa.split("/").filter(String);
var reconstructed = "";
for( var index in bb )
{
var dirNames = bb[index].split(":");
if(dirNames.length==1) reconstructed += "/" + dirNames[0];
else if(dirNames.length==2) reconstructed += "/" + dirNames[1];
}

You can use regex like this:
var str = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4";
var out = str.replace(/\/[^:\/]+:/g, "/");
alert(out);
This matches:
/
followed by one or more characters that is not a : or a /
followed by a :
and replaces all that with a / effectively eliminating the xxx:
Demo here: http://jsfiddle.net/jfriend00/hbUkz/

Like this:
var bb = aa.replace(/\/[a-z]+:/g, '/');
Change the [a-z] to include any characters that might appear in the prefix, or just use [^\/:].

var a = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4";
var b = a.replace(/\/[^\/]*:/g, "/");

aa = aa.replace(/\/[^:\/]\:/g, "/");
This function will replace every occurence of "/xxx:" by "/" using a RE, where xxx: is a prefix.

Related

replace a string partially with something else

lets say I have this image address like
https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
how is it possible to replace FILE_NAME.jpg with THUMB_FILE_NAME.jpg
Note: FILE_NAME and THUMB_FILE_NAME are not static and fix.
the FILE_NAME is not fixed and I can't use string.replace method.
eventually I don't know the File_Name
Use replace
.replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME")
or if you want to support multiple formats
.replace(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g, "THUMB_FILE_NAME")
Demo
var output = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b".replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME");
console.log( output );
Explanation
(?<=\/) matches / but doesn't remember the match
[^\/]* matches till you find next /
(?=(.jpg) ensures that match ends with .jpg
To match the FILE_NAME, use
.match(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g)
var pattern = /[\w-]+\.(jpg|png|txt)/
var c = 'https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
'
c.replace(pattern, 'YOUR_FILE_NAME.jpg')
you can add any format in the pipe operator
You can use the String's replace method.
var a = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
a = a.replace('FILE_NAME', 'THUMB_FILE_NAME');
If you know the format, you can use the split and join to replace the FILE_NAME.
let str = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
let str_pieces = str.split('/');
let str_last = str_pieces[str_pieces.length - 1];
let str_last_pieces = str_last.split('?');
str_last_pieces[0] = 'THUMB_' + str_last_pieces[0];
str_last = str_last_pieces.join('?');
str_pieces[str_pieces.length - 1] = str_last;
str = str_pieces.join('/');

how to replace words in string using javascript?

i have a string,
mystr = 'public\uploads\file-1490095922739.jpg';
i want to replace
public\uploads
with " ", so that i just want to extract only file name ie
file-1490095922739.jpg
or like,
\uploads\file-1490095922739.jpg
how can i do this, is there any methods for this in js or can we do it by replace method.
i am performing the following steps,
var imagepath1;
var imagepath = 'public\uploads\file-1490095922739.jpg';
unwantedChar = 'public|uploads';
regExp = new RegExp(unwantedChar , 'gi');
imagepath = imagepath.replace(regExp , '');
imagepath1 = imagepath;
$scope.model.imagepath = imagepath1.replace(/\\/g, "");
please suggest me optimized method.
var input = "public\\uploads\\file-1490095922739.jpg";
var result = input.replace("public\\uploads\\", "");
This is what you're looking for, no need for fancy regexs :). More information about replace can be found here.
Maybe I don't understand the issue - but wouldn't this work?
var mystr = 'public\uploads\file-1490095922739.jpg';
var filename = mystr.replace('public\uploads', '');
If you want to get the part of the string after the last backslash character, you can use this:
var filename = mystr.substr(mystr.lastIndexOf('\\') + 1);
Also note that you need to escape the backslash characters in your test string:
var mystr = 'public\\uploads\\file-1490095922739.jpg';
What about just doing:
var imagepath = 'public\\uploads\\file-1490095922739.jpg';
$scope.model.imagepath = imagepath.replace('public\\uploads\\', '');
instead of using a bunch of unnecessary variables?
This way you're getting the file path, removing public\uploads\ and then setting the file path to $scope.model.imagepath
Note that this will only work if the image file path always matches 'public\uploads\*FILENAME*'.
var url = '/anysource/anypath/myfilename.gif';
var filename = url.slice(url.lastIndexOf('/')+1,url.length);
Search for the last forward slash, and slice the string (+1 because you don't want the slash), with the length of the string to get the filename. This way, you don't have to worry about the path is at all times.

Split the date! (It's a string actually)

I want to split this kind of String :
"14:30 - 19:30" or "14:30-19:30"
inside a javascript array like ["14:30", "19:30"]
so I have my variable
var stringa = "14:30 - 19:30";
var stringes = [];
Should i do it with regular expressions? I think I need an help
You can just use str.split :
var stringa = "14:30 - 19:30";
var res = str.split("-");
If you know that the only '-' present will be the delimiter, you can start by splitting on that:
let parts = input.split('-');
If you need to get rid of whitespace surrounding that, you should trim each part:
parts = parts.map(function (it) { return it.trim(); });
To validate those parts, you can use a regex:
parts = parts.filter(function (it) { return /^\d\d:\d\d$/.test(it); });
Combined:
var input = "14:30 - 19:30";
var parts = input.split('-').map(function(it) {
return it.trim();
}).filter(function(it) {
return /^\d\d:\d\d$/.test(it);
});
document.getElementById('results').textContent = JSON.stringify(parts);
<pre id="results"></pre>
Try this :
var stringa = "14:30 - 19:30";
var stringes = stringa.split("-"); // string is "14:30-19:30" this style
or
var stringes = stringa.split(" - "); // if string is "14:30 - 19:30"; style so it includes the spaces also around '-' character.
The split function breaks the strings in sub-strings based on the location of the substring you enter inside it "-"
. the first one splits it based on location of "-" and second one includes the spaces also " - ".
*also it looks more like 24 hour clock time format than data as you mentioned in your question.
var stringa = '14:30 - 19:30';
var stringes = stringa.split("-");
.split is probably the best way to go, though you will want to prep the string first. I would go with str.replace(/\s*-\s*/g, '-').split('-'). to demonstrate:
var str = "14:30 - 19:30"
var str2 = "14:30-19:30"
console.log(str.replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
console.log(str2 .replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
Don't forget that you can pass a RegExp into str.split
'14:30 - 19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]
'14:30-19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]

remove 4 letters from a string, before the extension

How can you remove letters from a string in jquery
So for example if you had the following
var gif = "example_one.gif";
how could i out put it so it would show
"example.gif"
So remove the last four characters but keep the extension?
Regex approach
- Removes anything and including the underscore up until the extension
var gif = "example_one.gif";
gif = gif.replace(/(?=_).*(?=\.)/g,'');
DEMO
Explanation here
(?=_) Positive Lookahead - Assert that "underscore" can be matched
.* Matches any character (except newline)
(?=\.) Positive Lookahead - Assert that "period" can be matched
g modifier: Global. All matches (don't return on first match)
that what you want?
var gif = "example_one.gif" ;
gif = gif.substr(0, gif.indexOf("_")) + gif.substr(gif.indexOf("."), gif.length);
Walking through it the most basic way...
First find the .:
var gif = "example_one.gif";
var end = gif.lastIndexOf(".")
Then split the string:
var name_only = gif.substring(0,end)
Then take out what you want taken out:
var trimmed = name_only.substring(0,name_only.length-5)
Then put your extension back:
var cleaned = trimmed + gif.substring(end-1,gif.length)
Check it:
alert( cleaned )
Working fiddle: http://jsfiddle.net/digitalextremist/G27HN/
Or do it with a reusable function! http://jsfiddle.net/digitalextremist/wNu8U/
WITH ability to change length of trim job needed:
function cleanEnding( named, count ) {
if ( count == undefined ) count = 4
var end = named.lastIndexOf( "." )
var name_only = named.substring( 0, end )
var trimmed = name_only.substring( 0, name_only.length - count-1 )
var cleaned = trimmed + named.substring( end-1, named.length )
return cleaned
}
//de You CAN pass in a number after this.
//de The function defaults to trimming out 4 before the extension.
alert( cleanEnding( "example_one.gif" ) )
If its always the last four characters before the extension (and the extension is three characters):
var gif = "example_one.gif";
var gif2 = gif.substring(0, gif.length - 8) + gif.substring(gif.length - 4);
console.log(gif2);
http://jsfiddle.net/2cYrj/
var gif = "example_one.gif";
var str = gif.split('.');
str[0] = str[0].slice(0, -4);
gif = str.join('.');
console.log(gif);
var parts = gif.split('.');
var newstring = parts[0].substr(0, parts[0].length-4) + "." + parts[1];
gif.replace('_one', '')
Does this help you or you want it more general?
try this: gif.replace("_one","");

javascript regex to replace a substring

In javascript, how would I use a regular expression to replace everything to the right of "Source="
Assume, for example:
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSoruceValue="http://acme.com/vegiePage.aspx"
Goal is to get this value in outStr:
var outStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/vegiePage.aspx"
Thanks!!
Assumes that source= will always be at the end
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSourceValue="http://acme.com/vegiePage.aspx"
var outStr = inStr.replace( /(Source=).*/, "$1" + newSourceValue);
Is "Source" always linked to the first occurrance of "&"?
You could use
indexOf("&") + 7
(number of letters in the word "Source" + one for "=").
Then create the new string by appending the new source to the substring using the index from before.
string.replace( /pattern/, replace_text );
var outStr = inStr.replace( /&Source=.*$/, "&Source=" + newSoruceValue );
or
var outStr = inStr.replace( /(&Source=).*$/, "$1" + newSoruceValue )

Categories

Resources