m_gunns
m_gunns

Reputation: 547

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!!!

Upvotes: 3

Views: 275

Answers (3)

zdrsh
zdrsh

Reputation: 1667

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.

Upvotes: 3

styrr
styrr

Reputation: 829

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)".

Upvotes: 3

Senad Meškin
Senad Meškin

Reputation: 13756

This will do the trick, a little bit of regex

var img_name = "bottom.gif (0.43KB)".split(/[ ]\([0-9a-z\.]{0,}\)/gi)[0]

Upvotes: 1

Related Questions