Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery/JS replace text within a string

I am trying to see if I can remove some characters from the string that the below script creates:

$(".fileName").text()

The string that is created will be something like:

"bottom.gif (0.43KB)"

I want the string to be: "bottom.gif"

the issue: the image name can be anything. The size of the image will also varry. The only constant that I have to work with are: space after the image name "(" before the file size ")" after the file size

Any help would be great!!!

like image 837
m_gunns Avatar asked May 22 '26 18:05

m_gunns


2 Answers

var text = $(".fileName").text().split(' (')[0];

Example here

It splits the text string into an array everywhere this string ' (' occurs:

text[0] = "bottom.gif" 
text[1] = "0.43KB)"

and you need only text[0] for use.

note: If the ' (' doesn't exist it will return the whole string:

var text = $(".fileName").text().split('_')[0];

text[0]="bottom.gif (0.43KB)"
text[1]  error

so it is safe to use it with [0] and no check if the value is null.

like image 174
zdrsh Avatar answered May 25 '26 06:05

zdrsh


It's quite simple and will work with any file name:

var text = "bottom.gif (0.43KB)";
text = text.substring(0, text.lastIndexOf('(')-1);

experimentX's solution will fail for some file names. E.g.: "bottom (here is the problem).gif (0.43KB)".

like image 30
styrr Avatar answered May 25 '26 08:05

styrr