Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace some character from string (url)

Tags:

javascript

I tried to remove some character from a string, but it failed and I don't know why.

This is the code

path='url("https://www.example.com/folder/next/another/myfilename.jpg")';

var file = path.split('/'); 
console.log('file is: '+file);
file = file[file.length-1];
console.log('file is: '+file);
file=file.replace('/[")(]/g',''); // try also replace('/[")(]','') failed
console.log('file is: '+file);
return file;

In the console I read

file is: url("https:,,www.example.com,folder,next,another,myfilename.jpg")
file is: myfilename.jpg")
file is: myfilename.jpg")

I don't understand why the "() charachters by the replace function won't replaced.

Thanks for helping and explaining!

like image 378
mikeD Avatar asked Jan 28 '26 10:01

mikeD


2 Answers

Remove quotes in your regex:

function testFunction() {
    path='url("https://www.example.com/folder/next/another/myfilename.jpg")';

    var file = path.split('/'); 
    console.log('file is: '+file);
    file = file[file.length-1];
    console.log('file is: '+file);
    file=file.replace(/[")(]*/g, ''); 
    console.log('file is: '+file);
    return file;   
}
testFunction();

In console:

file is: url("https:,,www.example.com,folder,next,another,myfilename.jpg")
file is: myfilename.jpg")
file is: myfilename.jpg

Return value is "myfilename.jpg" now. Is it what youwhant?

like image 50
A. Denis Avatar answered Jan 30 '26 23:01

A. Denis


Correct regex to use here would be /[()"]*/g instead of '/[")(]/g'

like image 22
Surender Avatar answered Jan 30 '26 23:01

Surender