I need to grab a value from input field in a form, i need only the file name. The string looks like so:
var str = 'C:\Users\User\Desktop\file_name.ext';
If i try to run (yes, the backslash is escaped)
str.split(\\)[str.length-1]
It does not work, as the slashes in the string aren't escaped. Simple console.log(str) gives me C:UsersUserDesktopile_name.ext and you see where the problem is. How do i get around that?
'C:\Users\User\Desktop\file_name.ext'.split(/\\|//).pop();
Assume the backslashes are escaped. I'm confusing people by escaping my backslashes. The above string is "as is".
You need to escape the backslashes in your string:
"C:\\Users\\User\\Desktop\\file_name.ext".split("\\").pop();
var str = 'C:\\Users\\User\\Desktop\\file_name.ext';
var parts = str.split('\\');
var result = parts[parts.length - 1];
The solution, and link to fiddle fiddle
$(function () {
function getFileName(path) {
return path.match(/[-_\w]+[.][\w]+$/i)[0];
}
$('#data_up').change(function () {
var fileName = $(this).val();
$('#data').val('somepath/' + getFileName(fileName));
});
});
Related
I parse the data from website and try to change to a json object.
Here is my function:
function outPutJSON() {
for (var i = 0; i < movieTitle.length; i++) {
var handleN = movieContent[i];
console.log('===\n');
console.log(handleN);
data.movie.push({
mpvieTitle: movieTitle[i],
movieEnTitle: movieEnTitle[i],
theDate: theDate[i],
theLength: theLength[i],
movieVersion: movieVersion[i],
youtubeId: twoId[i],
content: movieContent[i]
});
};
return JSON.stringify(data);
}
console.log will print movieContent[0] like:
but i return JSON.stringfy(data);
it will become:
There are so many /n i want to remove it.
I try to change return JSON.stringfy(data); to this:
var allMovieData = JSON.stringify(data);
allMovieData = allMovieData.replace(/\n/g, '');
return allMovieData;
It's not working the result is the same.
How to remove /n when i use JSON.stringfy() ?
Any help would be appreciated . Thanks in advance.
In your data screenshots, you literally see "\n".
This probably means that the actual string doesn't contain a newline character (\n), but a escaped newline character (\\n).
A newline character would have been rendered as a linebreak. You wouldn't see the \n.
To remove those, use .replace(/\\n/g, '') instead of .replace(/\n/g, '')
just :=>
JSON.stringify(JSON.parse(<json object>))
JSON.stringify converts new lines (\n) and tab (\t) chars into string, so, when you will try to parse it, the string will contain those again.
So, you need to search the string \n, you can do that with something like that.
const stringWithNewLine = {
x: `this will conatin
new lines`
};
const json = JSON.stringify(stringWithNewLine);
console.log(json.replace(/\\n/g, ''))
I know this is an old question but it is always good to have options. You can use a string literal as a simple wrapper. The string literal will honor the string's line breaks, empty spaces etc. Like:
let jsonAsPrettyString = `${JSON.stringify(jsonObject, null, 2)}`;
Lets say I am receiving a string like so:
var string = "example_string"
var otherString = "example_string_two"
And I want to manipulate it to output like this:
string = "exampleString"
otherString = "ExampleStringTwo"
Basically, I want to find any underscore characters in a string and remove them. If there is a letter after the underscore, then it should be capitalized.
Is there a fast way to do this in regex?
You could look for the start of the string or underscore and replace the found part with an uppercase character.
var string= 'example_string_two';
console.log(string.replace(/(^|_)./g, s => s.slice(-1).toUpperCase()));
A regular expression like /_([a-zA-Z])/g will do with a proper callback function in String.prototype.replace. See snippet below.
function camelize (dasherizedStr) {
return dasherizedStr
.replace(/_([a-zA-Z])/g, function (m1, m2) {
return m2.toUpperCase()
});
}
console.log('example_string_foo:', camelize('example_string_foo'));
console.log('foo_Bar:', camelize('foo_Bar'));
Yeah you could use regex methods and simply replace the underscore and i'll give you an example :
var string = "example_string"
string.replace('_','');
But you could also do this in classic JS, which is pretty fast in on it's self
Example:
var string = "example_string"
string.split('_').join('');
If you are looking for something more, please comment below.
You can easily replace using JavaScript
var string= 'example_string_two';
console.log(string.replaceAll('_', ' '))
Output : 'example string two'
you can replace any word, underscore, dashes using javascript
here is code
var str= 'example_string_two';
console.log(var newStr = str.replace("_", " "));
output:
examplestringtwo
I have a string in which I want to replace an occurence which I am not being able to achieve following is the code
var code="user_1/has some text and user_1? also has some text";
newcode=code.replace(/user_1//g,'_');
One more thing if i have to replace a string from another string how to do?
example.
var replacestring="user_1";
var code="user_1/some value here for some user";
var newcode=code.replace(/+replacestring+/g,'_');
/ is a special char thus needs to be escaped with \ before it:
var code = "user_1/has some text and user_1? also has some text";
var newcode = code.replace(/user_1\//g, '_');
alert(newcode);
Live DEMO
if you want to replace all user_1, use this:
var code = "user_1/has some text and user_1? also has some text";
var newcode = code.replace(/user_1/g, '_');
alert(newcode);
Live DEMO
Escape the / in the regex using \
newcode=code.replace(/user_1\//g,'_');
For your comment
#Vega I have another confusion. can i use a value in a string to pass
instead of user_1/ for replacement? what would be the syntax?
You can initialize RegEx object like below,
var userName = 'user_1/';
var newcode = code.replace(new RegExp(userName, 'g'), '_');
Read More about RegEx
Here is the Original string :
var str = " a vartiable";
and I need this part:
str = "https://sjobs.brassring.com/1033/ASP/TG/cim_jobdetail.asp?SID=^cJgiKPhGBHyn5VRSb9gbJg0K2T88FrLqHyAtd6hd5pJ7JeXxNyq0VatKCq3jYWp/&jobId=385594&type=hotjobs&JobReqLang=141&JobSiteId=5239&JobSiteInfo=385594_5239&GQId=0";
In other words, I need to remove the tag <a> and the document.href value
Thanks guys.
How about:
var str = " a vartiable";
str.replace(/^<a href="(https.*?)cim_home\.asp.*?'(cim_jobdetail\.asp.*)'.*$/, "$1$2");
produces:
"https://sjobs.brassring.com/1033/ASP/TG/cim_jobdetail.asp?SID=^cJgiKPhGBHyn5VRSb9gbJg0K2T88FrLqHyAtd6hd5pJ7JeXxNyq0VatKCq3jYWp/&jobId=385594&type=hotjobs&JobReqLang=141&JobSiteId=5239&JobSiteInfo=385594_5239&GQId=0"
Something simple like the following should work...
href="(.*?)"
here's the code u want:
var str = ' a vartiable'
var url = /\"(.*?)\"/str
that's how you match, here's how you strip it out:
str.replace(/\"(.*?)\"/, "$1");
the \"(.*?)\" gives the first minimal set of characters between two " characters the id of $1 then the second argument to the replace function tells it to replace the whole string with what's contained in $1
Also, if you use jQuery, this becomes pretty trivial:
var url = $("a").attr("href");
I have a string like foobar1, foobaz2, barbar23, nobar100 I want only foobar, foobaz, barbar, nobar and ignoring the number part.
If you want to strip out things that are digits, a regex can do that for you:
var s = "foobar1";
s = s.replace(/\d/g, "");
alert(s);
// "foobar"
(\d is the regex class for "digit". We're replacing them with nothing.)
Note that as given, it will remove any digit anywhere in the string.
This can be done in JavaScript:
/^[^\d]+/.exec("foobar1")[0]
This will return all characters from the beginning of string until a number is found.
var str = 'foobar1, foobaz2, barbar23, nobar100';
console.log(str.replace(/\d/g, ''));
Find some more information about regular expressions in javascript...
This should do what you want:
var re = /[0-9]*/g;
var newvalue= oldvalue.replace(re,"");
This replaces al numbers in the entire string. If you only want to remove at the end then use this:
var re = /[0-9]*$/g;
I don't know how to do that in JQuery, but in JavaScript you can just use a regular expression string replace.
var yourString = "foobar1, foobaz2, barbar23, nobar100";
var yourStringMinusDigits = yourString.replace(/\d/g,"");