Remove all content after last '\' is not working - javascript

I'm trying to rename a document, I want to remove all the content after the last '\' and then give it another name.
I did it like this but it doesn't seem to be working:
var newDocName = documentPath.replace(/\/$/, '');
var newDocName = newDocName + "\test.pdf";
The '\' doesn't get removed after the first line of code.
Any idea what am I doing wrong?

/\/$/ means you want to match a / if it's the last character in the string meaning this code would replace the very last / if, and only if, it's at the end of the string.
If you want to remove the content after the last \ then you can use a combination of split to split the string on \s then use slice to get everything but the last element. Finally, use join to bring them all back together.
var uri = 'path\\to\\my\\file.ext';
var parts = uri.split('\\');
var withoutFile = parts.slice(0, parts.length - 1);
var putItBackTogether = withoutFile.join('\\');
var voila = putItBackTogether + '\\new-file.name';
console.log(voila);

It is forward slash, use \\ istead.

Try to substitute it for:
var newDocName = documentPath.replace(/\\/$/, '');

Your REGEX has a bad format: you should escape your backquotes (\).
So it may be:
var newDocName = documentPath.replace(/[\\/]$/, '');
var newDocName = newDocName + "\\test.pdf";
This regular expression will search for \ or / at the end ($) of you path. You could use regex101 to test your regular expressions.
You also should consider not using regular expressions when you don’t need them:
var newDocName = documentPath[documentPath.length - 1] == "\\" ? documentPath + "test.pdf" : documentPath + "\\test.pdf";

Related

How to remove the first and the last character of a string

I'm wondering how to remove the first and last character of a string in Javascript.
My url is showing /installers/ and I just want installers.
Sometimes it will be /installers/services/ and I just need installers/services.
So I can't just simply strip the slashes /.
Here you go
var yourString = "/installers/";
var result = yourString.substring(1, yourString.length-1);
console.log(result);
Or you can use .slice as suggested by Ankit Gupta
var yourString = "/installers/services/";
var result = yourString.slice(1,-1);
console.log(result);
Documentation for the slice and substring.
It may be nicer one to use slice like :
string.slice(1, -1)
I don't think jQuery has anything to do with this. Anyway, try the following :
url = url.replace(/^\/|\/$/g, '');
If you dont always have a starting or trailing slash, you could regex it. While regexes are slower then simple replaces/slices, it has a bit more room for logic:
"/installers/services/".replace(/^\/?|\/?$/g, "")
# /installers/services/ -> installers/services
# /installers/services -> installers/services
# installers/services/ -> installers/services
The regex explained:
['start with' ^] + [Optional?] + [slash]: ^/?, escaped -> ^\/?
The pipe ( | ) can be read as or
['ends with' $] + [Optional ?] + [slash] -> /?$, escaped -> \/?$
Combined it would be ^/?|/$ without escaping. Optional first slash OR optional last slash.
Technically it isn't "optional", but "zero or one times".
You can do something like that :
"/installers/services/".replace(/^\/+/g,'').replace(/\/+$/g,'')
This regex is a common way to have the same behaviour of the trim function used in many languages.
A possible implementation of trim function is :
function trim(string, char){
if(!char) char = ' '; //space by default
char = char.replace(/([()[{*+.$^\\|?])/g, '\\$1'); //escape char parameter if needed for regex syntax.
var regex_1 = new RegExp("^" + char + "+", "g");
var regex_2 = new RegExp(char + "+$", "g");
return string.replace(regex_1, '').replace(regex_2, '');
}
Which will delete all / at the beginning and the end of the string. It handles cases like ///installers/services///
You can also simply do :
"/installers/".substring(1, string.length-1);
You can use substring method
s = s.substring(0, s.length - 1) //removes last character
another alternative is slice method
if you need to remove the first leter of string
string.slice(1, 0)
and for remove last letter
string.slice(0, -1)
use .replace(/.*\/(\S+)\//img,"$1")
"/installers/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services
"/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services
It is too nicer shortcode.
response.data.slice(1,-1) // "Prince"
-> Prince
url=url.substring(1,url.Length-1);
This way you can use the directories if it is like .../.../.../... etc.

Replacing all symbols in a javascript string

Hi all ia m trying to replace all characters of "+" in a string by using the code below:
var findValue = "+";
var re = new RegExp(findValue, 'g');
searchValueParam = searchValueParam.replace(re, " ");
However i recieve this exception:
SyntaxError: Invalid regular expression: nothing to repeat
previously i applied just searchValueParam = searchValueParam.replace("+", " "); but that only replaces the first occurrence, not all.
Any suggestions?
For multiple replacements you need to use regex with the global (g) modifier, however + has a special meaning (the previous item 1 or more times), so it needs to be escaped.
searchValueParam = searchValueParam.replace(/\+/g,' ');
You need to escape the + sign:
searchValueParam.replace(/\+/g, " ");
If you want to keep the code you have, replace
var findValue = '+';
with
var findValue = '\\+';
Plus has a special meaning (quantifier) in a regular expression. This is why we need to escape it with a backslash: \+. However, when you place this in a string, the backslash itself has to be escaped as it has a special meaning in a string. This is how we end up with '\\+'.
In conclusion, this
var re = new RegExp('\\+', 'g')
is equivalent to this
var re = /\+/g;

How to ignore newline in regexp?

How to ignore newline in regexp in Javascript ?
for example:
data = "\
<test>11\n
1</test>\n\
#EXTM3U\n\
"
var reg = new RegExp( "\<" + "test" + "\>(.*?)\<\/" + "test" + "\>" )
var match = data.match(reg)
console.log(match[1])
result: undefined
In JavaScript, there is no flag to tell to RegExp() that . should match newlines. So, you need to use a workaround e.g. [\s\S].
Your RegExp would then look like this:
var reg = new RegExp( "\<" + "test" + "\>([\s\S]*?)\<\/" + "test" + "\>" );
You are missing a JS newline character \ at the end of line 2.
Also, change regexp to:
var data = "\
<test>11\n\
1</test>\n\
#EXTM3U\n\
";
var reg = new RegExp(/<test>(.|\s)*<\/test>/);
var match = data.match(reg);
console.log(match[0]);
http://jsfiddle.net/samliew/DPc2E/
By reading this one: How to use JavaScript regex over multiple lines?
I came with that, which works:
var data = "<test>11\n1</test>\n#EXTM3U\n";
reg = /<test>([\s\S]*?)<\/test>/;
var match = data.match(reg);
console.log(match[1]);
Here is a fiddle: http://jsfiddle.net/Rpkj2/
Better you can use [\s\S] instead of . for multiline matching.
It is the most common JavaScript idiom for matching everything including newlines. It's easier on the eyes and much more efficient than an alternation-based approach like (.|\n).
EDIT: Got it:
I tried to use this regex in notepad++ But the problem is that it finds the whole text from beginning to end
MyRegex:
<hostname-validation>(.|\s)*<\/pathname-validation> (finds everything)
/<hostname-validation>(.|\s)*<\/pathname-validation>/ (finds nothing)
/\<hostname-validation\>([\s\S]*?)\<\/pathname-validation\>/ (finds nothing)
**<hostname-validation>([\s\S]*?)<\/pathname-validation> (my desired result)**
The text where I use in:
<hostname-validation>www.your-tag-name.com</hostname-validation>
<pathname-validation>pathname</pathname-validation> <response-validation nil="true"/>
<validate-absence type="boolean">false</validate-absence> (...) <hostname-validation>www.your-tag-name.com</hostname-validation>
<pathname-validation>pathname</pathname-validation> <response-validation nil="false"/>
<validate-absence type="boolean">false</validate-absence> (...) <hostname-validation>www.your-tag-name.com</hostname-validation>
<pathname-validation>pathname</pathname-validation> <response-validation nil="true"/>
<validate-absence type="boolean">false</validate-absence> (...)

How can I find a specific string and replace based on character?

I'm trying to find a specific character, for example '?' and then remove all text behind the char until I hit a whitespace.
So that:
var string = '?What is going on here?';
Then the new string would be: 'is going on here';
I have been using this:
var mod_content = content.substring(content.indexOf(' ') + 1);
But this is not valid anymore, since the specific string also can be in the middle of a string also.
I haven't really tried anything but this. I have no idea at all how to do it.
use:
string = string.replace(/\?\S*\s+/g, '');
Update:
If want to remove the last ? too, then use
string = string.replace(/\?\S*\s*/g, '');
var firstBit = str.split("?");
var bityouWant = firstBit.substring(firstBit.indexOf(' ') + 1);

Am I using pattern matching correctly here?

I have the following code. Given that the variable u1 can be any of the following:
NBSLoan|Accept|PPI+No|60Months
NBSLoan|Refer|PPI+No|60Months
DeBSLoan|Accept|PPI+No|60Months
Also, the last part 60Months will always be different, can I pattern match using the following JavaScript? Do I need to put in a special character for the pipe | symbol? Or will this not work as I'm trying to match only the first part of a longer string?
<script type="text/javascript">
var u1 = 'NBSLoan|Accept|PPI+No|60Months';
var n_accept = /^NBSLoan|Accept$/;
var n_refer = /^NBSLoan|Refer$/;
var d_accept = /^DeBSLoan|Accept$/;
if (u1.match(n_accept)) {
var pvnPixel = '<img src="https://url1.com"/>';
document.write(pvnPixel);
}
else if (u1.match(n_refer)) {
var pvnPixel2 = '<img src="url2.com"/>';
document.write(pvnPixel2);
}
else if (u1.match(d_accept)) {
var pvnPixel3 = '<img src="url3.com"/>';
document.write(pvnPixel3);
}
</script>
Do I need to put in a special character for the pipe | symbol? Or will this not work as I'm trying to match only the first part of a longer string?
Both.
You need to escape the pipe symbol with a backslash to match a literal pipe character. Without the backslash it means alternation.
You also need to remove your end of line anchor.
Try this regular expression:
/^NBSLoan\|Accept/
Why don't you first split fields with split('|'):
function dispatch(u) {
var parts = u.split('|'),
key = parts[0] + "_" + parts[1];
disp_table = {
'NBSLoan_Accept':'url1.com',
'NBSLoan_Refer':'url2.com',
'DeBSLoan_Accept':'url3.com'
},
url = disp_table[key];
url && document.write("<img src=\""+url+"\"/>");
}
You want to also remove the $ (it signifies the end of string) or add a .* to capture all the other characters:
To lose the end:
/^NBSLoan\|Accept/
To match and capture the other characters:
/^NBSLoan\|Accept.*$/

Categories

Resources