Replace multiple strings with Javascript - javascript

I'm trying to transform this string
.jpg,.gif,.png
into this (not dots and space after comma)
jpg, gif, png
I thought that something like PHP's str_replace for arrays in JS will do the trick, so I found this post, and specifically this answer. I tried it but is't not working as expected. I'm getting a blank string... Am I doing something wrong?
JS
String.prototype.replaceArray = function(find, replace)
{
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++)
{
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
};
var my_string = ".jpg,.gif,.png";
alert(my_string.replaceArray([".", ","],["", ", "]));
Link to jsfiddle

The first thing you're trying to replace is a period ("."), which is a regular expression for any character. You need to escape it: "\\."

I just did this:
var target = '.jpg,.gif,.png';
target = target.replace(/\\./g, '');
target = target.replace(/,/g, ', ');
I'm sure it can be done more efficiently, but this will get the job done.

You can change your fn to this :
function strToArr(str)
{
var res = str.replace(/\./g, "");
return res.split(",");
}

Related

How can I extract a part of this url with JavaScript?

I have an url that looks like this:
http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg
I want to extract hw6dNDBT.jpg, from the url above.
I tried playing around with regex patterns /img\/.*-/ but that
matches with img/hw6dNDBT-.
How can I do this in JavaScript?
try this:
var url = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
var filename = url.match(/img\/(.*)-[^.]+(\.[^.]+)/).slice(1).join('');
document.body.innerHTML = filename;
i would use split() method:
var str = "http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg";
var strArr = str.split("/");
var size = strArr.length - 1;
var needle = strArr[size].split("-");
var fileTypeArr = strArr[size].split(".");
var name = needle[0]+"."+fileTypeArr[fileTypeArr.length-1];
name should now be your searched String so far it contains no / inside it
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
/[^\/]+$/ should match all characters after the last / in the URL, which seems to be what you want to match.
No regex:
//this is a hack that lets the anchor tag do some parsing for you
var parser = document.createElement('a');
parser.href = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
//optional if you know you can always trim the start of the path
var path = parser.pathname.replace('/assets/uploads/');
var parts = path.split('/');
var img = '';
for(var i=0; i<parts.length; i++) {
if (parts[i] == 'img') {
//since we know the .jpg always follows 'img/'
img = parts[i+1];
}
}
Ah, you were so close! You just need to take your regex and use a capturing group, and then add a littttle bit more!
img\/(.*)-.*(\..*)
So, you can use that in this manner:
var result = /img\/(.*)-.*(\..*)/.exec();
var filename = result[1] + result[2];
Honestly capturing the .jpg, is a little excessive, if you know they are all going to be JPG images, you can probably just take out the second half of the regex.
Incase you are wondering, why do we uses result[1] and result[2]? Because result[0] stores the entire match, which is what you were getting back. The captured groups, which is what we create when we use the parentheses, are stored as the indexes after 0.
Here is some one-liner:
var myUrl = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg',
myValue = myUrl.split('/').pop().replace(/-(?=\d).[^.]+/,'');
We take everything after the last slash then cut out the dimension part.

Javascript replace string in a string using value from array

I want to replace string in a paragraph where string may be combination of alphanumeric and slashes.
What i did:
var arrayFind = new Array('s\\if','t\\/');
var arrayReplace = new Array('If','q');
var arrayFindLength = arrayFind.length;
function replaceRightChar(str, parFind, parReplace){
for (var i = 0; i < arrayFindLength; i++) {
regex = new RegExp(parFind[i], "g");
str = str.replace(regex, parReplace[i]);
}
alert(str);
}
var mainData="s\\if t\\/ h\\ s\\";
replaceRightChar(mainData, arrayFind, arrayReplace);
Error:
Uncaught SyntaxError: Invalid regular expression: /s/: \ at end of pattern
My tests do not end up with any error.
You did have a problem with double escaping, though.
Array('s\\if','t\\/');
should be (if I got right what you want)
Array('s\\\\if','t\\\\/');
Working example: jsfiddle
Edit: I still think that the problem is the double escaping. I updated my fiddle to test all the possible combinations.
Essentially I doubled the arrayFind
var arrayFind1 = new Array('s\\if','t\\/');
var arrayFind2 = new Array('s\\\\if','t\\\\/');
and the mainData
var mainData1="s\if t\/ h\\ s\\";
var mainData2="s\\if t\\/ h\\ s\\";
and quadruplicated the call
replaceRightChar(mainData1, arrayFind1, arrayReplace);
replaceRightChar(mainData1, arrayFind2, arrayReplace);
replaceRightChar(mainData2, arrayFind1, arrayReplace);
replaceRightChar(mainData2, arrayFind2, arrayReplace);
I guess the first or the fourth call are what you need
Just for sake of clarity I add another answer instead of editing my existing one. The point is that when the string comes from a textarea it is not really as if it came from var str=...
It is almost the same, but for escaping.
What works in that case is to use regular expressions defined with the /.../g notation and not with the new RegExp('...','g') notation or to double escape things.
Here a working example. The code:
var arrayFindRE = new Array(/s\\if/g,/t\\\//g);
var arrayFindStr = new Array('s\\\\if','t\\\\/');
var arrayReplace = new Array('If','q');
var arrayFindLength = arrayFindRE.length;
function replaceRegExp(str){
for (var i = 0; i < arrayFindLength; i++) {
str = str.replace(arrayFindRE[i], arrayReplace[i]);
}
alert(str);
}
function replaceString(str){
for (var i = 0; i < arrayFindLength; i++) {
var re = new RegExp(arrayFindStr[i],'g');
str = str.replace(re, arrayReplace[i]);
}
alert(str);
}
(here replaceRegExp and replaceString are called with the value of a textarea in the fiddle).

Regex doesn't seem to work properly in my code

What I am trying to do is turn, for example "{{John}}" into "John".
First I am parsing from a string:
var parametrar = content.match(/[{{]+[Aa-Åå]+[}}]/g);
Here regex works fine and it parses as it should. I need to parse the "{}" to find stuff in the string.
But then I'm trying to parse out the "{}" from each "parametrar":
for (var i = 0; i < parametrar.length; i++) {
parametrar = parametrar[i].replace(/[{}]/g, "");
}
When I alert "parametrar" all I get is one "a". I have no idea what I'm doing wrong here, seems it should work.
Try to add greedy matching to maque's answer with using question mark(?).
"{{John}}".replace(/\{\{(.*?)\}\}/g,"$1");
It extracts "John" properly from "{{John}} and Martin}}" input. Otherwise it matches to "John}} and Martin".
You can match the name with braces around and then just use the first capturing group (m[1]):
var re = /\{{2}([a-zA-ZÅå]+)\}{2}/g;
var str = '{{John}}';
if ((m = re.exec(str)) !== null) {
paramterar = m[1];
alert(paramterar);
}
If you have a larger string that contains multiple {{NAME}}s, you can use the code I suggested in my comment:
var re = /\{{2}([a-zA-ZÅå]+)\}{2}/g;
var str = 'My name is {{John}} and {{Vasya}}.';
var arr = [];
while ((m = re.exec(str)) !== null) {
paramterar = m[1];
arr.push(m[1]);
}
alert(arr);
alert(str.replace(/([a-zA-ZÅå])\}{2}/g,"$1").replace(/\{{2}(?=[a-zA-ZÅå])/g, ""))
I have also fixed the character class to only accept English letters + Å and å (revert if it is not the case, but note that [Aa-Åå] is not matching any upper case Englihs letters from B to Z, and matches characters like §.) Please check the ANSI table to see what range you need.
Just do it like that:
"{{John}}".replace(/\{\{(.*)\}\}/g,"$1");
So you are searching for string that have double '{' (these needs to be escaped), then there is something (.*) then again '}' and your output is first match of the block.
Try this:
var parametrar = content.replace(/\{\{([a-åA-Å]+)\}\}/g, "$1");
This gives you a "purified" string. If you want an array, than you can do this:
var parametrar = content.match(/\{\{[a-åA-Å]+\}\}/g);
for (var i = 0, len = parametrar.length; i < len; i++) {
parametrar = parametrar[i].replace(/\{\{([a-åA-Å]+)\}\}/g, "$1");
}

Trimming a string from the end in Javascript

In Javascript, how can I trim a string by a number of characters from the end, append another string, and re-append the initially cut-off string again?
In particular, I have filename.png and want to turn it into filename-thumbnail.png.
I am looking for something along the lines of:
var sImage = "filename.png";
var sAppend = "-thumbnail";
var sThumbnail = magicHere(sImage, sAppend);
You can use .slice, which accepts negative indexes:
function insert(str, sub, pos) {
return str.slice(0, pos) + sub + str.slice(pos);
// "filename" + "-thumbnail" + ".png"
}
Usage:
insert("filename.png", "-thumbnail", -4); // insert at 4th from end
Try using a regular expression (Good documentation can be found at https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions)
I haven't tested but try something like:
var re = /(.*)\.png$/;
var str = "filename.png";
var newstr = str.replace(re, "$1-thumbnail.png");
console.log(newstr);
I would use a regular expression to find the various parts of the filename and then rearrange and add strings as needed from there.
Something like this:
var file='filename.png';
var re1='((?:[a-z][a-z0-9_]*))';
var re2='.*?';
var re3='((?:[a-z][a-z0-9_]*))';
var p = new RegExp(re1+re2+re3,["i"]);
var m = p.exec(file);
if (m != null) {
var fileName=m[1];
var fileExtension=m[2];
}
That would give you your file's name in fileName and file's extension in fileExtension. From there you could append or prepend anything you want.
var newFile = fileName + '-thumbnail' + '.' + fileExtension;
Perhaps simpler than regular expressions, you could use lastindexof (see http://www.w3schools.com/jsref/jsref_lastindexof.asp) to find the file extension (look for the period - this allows for longer file extensions like .html), then use slice as suggested by pimvdb.
You could use a regular expression and do something like this:
var sImage = "filename.png";
var sAppend = "-thumbnail$1";
var rExtension = /(\.[\w\d]+)$/;
var sThumbnail = sImage.replace(rExtension, sAppend);
rExtension is a regular expression which looks for the extension, capturing it into $1. You'll see that $1 appears inside of sAppend, which means "put the extension here".
EDIT: This solution will work with any file extension of any length. See it in action here: http://jsfiddle.net/h4Qsv/

Javascript regex - split string

Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
Eg, if I have this string:
hello/world
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
hello/wo\/rld
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
hello
wo\/rld
test it at ideone.com
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
Here's a way adapted from the techniques in this blog post:
var str = "Testing/one\\/two\\/three";
var result = str.replace(/(\\)?\//g, function($0, $1){
return $1 ? '/' : '[****]';
}).split('[****]');
Live example
Given:
Testing/one\/two\/three
The result is:
[0]: Testing
[1]: one/two/three
That first uses the simple "fake" lookbehind to replace / with [****] and to replace \/ with /, then splits on the [****] value. (Obviously, replace [****] with anything that won't be in the string.)
/*
If you are getting your string from an ajax response or a data base query,
that is, the string has not been interpreted by javascript,
you can match character sequences that either have no slash or have escaped slashes.
If you are defining the string in a script, escape the escapes and strip them after the match.
*/
var s='hello/wor\\/ld';
s=s.match(/(([^\/]*(\\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\\/g,'')
/* returned value: (String)
hello
wor/ld
*/
Here's an example at rubular.com
For short code, you can use reverse to simulate negative lookbehind
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\\(?:\\\\)*(?:[^\\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
but to be efficient, it's probably better to split on /[/]/ and then walk the array and rejoin elements that have an escape at the end.
Something like this may take care of it for you.
var str = "/hello/wo\\/rld/";
var split = str.replace(/^\/|\\?\/|\/$/g, function(match) {
if (match.indexOf('\\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);

Categories