Javascript replace() method not working - javascript

I have this URL :
http://example.com/example/sample/example.jpg
I want to have this :
http:\ /\ /example.com\ /example\ /sample\ /example.jpg
I wrote this code :
function addslashes(str) {
return str.replace('/', '\/');
}
var url = http://example.com/example/sample/example.jpg
var t = addslashes(url);
alert(t);
As an alert, I still get the old URL. What's wrong with this code?
Thanks.

If you want to print \ you must escape it with another backslash.
function addslashes(str) {
return str.replace(/\//g, '\\/');
}
Also, if you want the replace function to replace all occurrences, you must pass a regex with a g modifier instead of a string. If you pass a string it will only replace the first match and then end but with the modifier it will find all matches.

try this code fiddle:
function addslashes(str) {
return str.replace(/\//g, '\\/');
}
you need to add the g to set it to global, to replace all the '/' and in the replacing string you need to add '\'.

You have to add an additinal backslash to escape it right.
With replace you would only replace the first match. You can also use Regular expression as you can see on the other posts. But you can also use it with simple split and join functions
function addslashes(url) {
url.split('/').join('\\/');
}
Demo

Related

javascript : problem with regular expression

I'm trying to validate the value of an input text field with the following code:
function onBlurTexto(value) {
var regexNIT = "([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])";
regexCompilado = new RegExp(regexNIT);
if (!(regexCompilado.test(value))) {
alert("Wrong character in text :(");
return false;
} else {
return true;
}
}
But when i enter this text:
!65a
the function returns true (as you can see, the "!" character does not exist in the regular expression)
I'm not an expert in regular expressions, so i think i am missing something in the building of this reg.exp.
How can i put this regular expression to work?
Thanks in advance.
EDIT
i am so sorry ... i should remove the references to the variable "regexpValidar" before posting the issue. I modified the sample. Thanks #TecBrat
You should provide the start (^) and end ($) flags to your regex. Now you are matching 65a since you have alternate sets.
This should work /^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$/g
Demo: https://regex101.com/r/zo2MpN/3
RegExp.test looks for a match in the string, it doesn't verify that the whole string matches the regex. In order to do the latter, you need to add start and end anchors to your regex (i.e. '^' at the start and '$' at the end, so you have "^your regex here$").
I also just noticed that your regex is currently matching only one character. You probably want to add a '+' after the parens so that it matches one or more:
"^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$"
This is wrong. the variable you use doesn't has anything. Try this instead.
var regexCompilado = new RegExp(regexNIT);

Regex return undefined in a JavaScript String

I have a little code snippet where I use Regular Expressions to rip off punctuation, numbers etc from a string. I am getting undefined along with output of my ripped string. Can someone explain whats happening? Thanks
var regex = /[^a-zA-z\s\.]|_/gi;
function ripPunct(str) {
if ( str.match(regex) ) {
str = str.replace(regex).replace(/\s+/g, "");
}
return str;
}
console.log(ripPunct("*#£#__-=-=_+_devide-00000110490and586#multiply.edu"));
You should pass a replacement pattern to the first replace method, and also use A-Z, not A-z, in the pattern. Also, there is no point to check for a match before replacing, just use replace directly. Also, it seems the second chained replace is redundant as the first one already removes whitespace (it contains \s). Besides, the |_ alternative is also redundant since the [^a-zA-Z\s.] already matches an underscore as it is not part of the symbols specified by this character class.
var regex = /[^a-zA-Z\s.]/gi;
function ripPunct(str) {
return str.replace(regex, "");
}
console.log(ripPunct("*#£#__-=-=_+_devide-00000110490and586#multiply.edu"));

match only the last instance of a pattern with Javascript regexp

I want to remove size data from a file name like
var src = 'http://az648995.vo.msecnd.net/win/2015/11/Halo-1024x551.jpg';
src = src.replace(
/-\d+x\d+(.\S+)$/,
function( match, contents, offset, s ) {
return contents;
}
);
this works as expected and i get
http://az648995.vo.msecnd.net/win/2015/11/Halo.jpg
But if I have a filename like
http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.jpg
it returns
http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-1024x512.jpg
instead of the desired
http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000.jpg
Your regex does not work as expected primarily because of an unescaped dot in (.\S+)$ part. An unescaped . matches any character but a newline. However, \S matches any non-whitespace, including a .. Besides unnecessary backtracking, you may get an unexpected result with a string like http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.MORE_TEXT_HERE.jpg.
Assuming the extension is the part of a string after the last dot, you can use
-\d+x\d+(\.[^.\s]+)$
See regex demo
The nagated character class [^.\s] matches any character but whitespace and a literal . symbol. Note that there is no point in using a callback function inside a replace, you can use a mere $1 backreference.
JS demo:
var src = 'http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.jpg';
src = src.replace(/-\d+x\d+(.[^.\s]+)$/, "$1");
document.body.innerHTML = src;
Try escaping the . and you will be fine:
/-\d+x\d+(\.\S+)$/
Slightly change the regex to be a little more explicit:
/-\d+x\d+(\.[^\s-]+)$/
The regex can be simplified to the following
Replace
-\d+x\d+(\.\S+)
With
$1

How to replace last part of URL using Regex and jQuery?

I'm not using REGEX very often so I don't know it well.
Want to match last digits before / end of string.
so my regex will be\d+/$
Now I want to replace matched part of href inside the link.
First thing
SyntaxError: illegal character
var regex = \d+/$
so I escaped it (I think) var regex = /\d+//$
I thought it will be simple from now:
$('a').attr('href').replace(regex,'00/')
But it seems no use.
I'm using firebug console for testing
Solution
url = "www.example.com/event/detail/46/"
var value = url.substring(url.lastIndexOf('/') + 1);
url = url.replace(value, '00')
What you seem to want is this :
$('a').attr('href', function(_,h){ return h.replace(/\d+\/$/,'00/') });
A slash is escaped as \/ in a regex literal, not as //.
$(selector).attr(name, fun) will apply the function to each element.
In escaping use \ not /.
So this will be
var regex = /\d+\$/

How would I make a regular expression that would mean /some string/ either followed by a line break or not?

function(input){
return input.replace(/teststring/ig, "adifferentstring");
}
I want to replace "teststring" and "teststring\n" with "adifferentstring"
In regex, to match a specific character you can place it in brackets:
[\n]
To make the match "optional", you can follow it with a ?:
[\n]?
In your exact example, your full regex could be:
teststring[\n]?
So, your function would look like:
function replace(input) {
return input.replace(/teststring[\n]?/ig, "adifferentstring");
}
I'd suggest going with matching characters in brackets as this makes for easy expansion; consider, for instance, that you want to match Window's newlines (a carriage-return + a newline):
teststring[\r\n]?
Try
function(input){
return input.replace(/teststring\n?/ig, "adifferentstring");
}
Try .replace(/teststring[\n]?/ig,"adifferentstring");
It would be something like this:
var re = /teststring([\n]?)/ig;
So then your replace statement would look about like this:
return input.replace(re,"adifferentstring");
Here's a fiddle showing the regex works.
And then a fiddle showing the replace operation working.
Edit:
Actually, thinking about the problem a little further, if your regex does match a carriage return or new line character, that would need to get put back into the replacing string. The same regex I posted originally will work but you will need this replace statement instead (with the $1 denoting the first group in parantheses.
return input.replace(re,"adifferentstring$1");
fiddle

Categories