Random character in RegEx replace - javascript

I want to replace G$0 in the string gantt(G$0,$A4,$B4) with gantt(<>G$0<>,$A4,$B4). So I have the following code:
var str = '=gantt(G$0,$A4,$B4) ';
var val = "G$0";
var val2 = val.replace(/\$/, "\\$")
var reg = new RegExp(val2, 'g');
var str = str.replace(reg, '<>' + val + '<>');
The result in IE is: =gantt(<>GG$0<>,$A4,$B4)  (note the GG). The problem seems to be IE10 specific.
Why is this happening, is this an IE bug?
The replace should assume a string could contain multiple instances of **G$0**.

There's no need to use RegEx at all. Stick to regular string replacement, and you won't have to escape the val string.
var str = '=gantt(G$0,$A4,$B4) ';
var val = "G$0";
var result = str.replace(val, '<>' + val + '<>');
If you want to replace multiple instances of val this can be done with .split and .join:
var str = '=gantt(G$0,$A4,$B4,G$0) ';
var val = "G$0";
var result = str.split(val).join('<>' + val + '<>');

Related

Split a String till a word in javascript

I have to split a string till a word in JavaScript.
var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.join('|');
var siteUrlCurrent = urlCurrent.split(siteNamesJoin);
Here, I have to split the urlCurrent string using the words in the array. so that at the end I have to get www.example.com/web/americas. I am not getting the regex for that.
You may use
new RegExp("^.*?(?:" + siteNamesJoin + "|$)")
The pattern will look like
^.*?(?:americas|international|europe|asia-pacific|africa-middle-east|russia|india|$)
See the regex graph:
Details
^ - start of string
.*? - any 0 or more chars other than line break chars, as few as possible
(?:americas|international|europe|asia-pacific|africa-middle-east|russia|india|$) - any of the values in between pipes or end of string.
See JS demo:
var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.join('|');
var match = urlCurrent.match(new RegExp("^.*?(?:" + siteNamesJoin + "|$)"));
var siteUrlCurrent = match ? match[0] : "";
console.log(siteUrlCurrent);
NOTE: if the siteNames "words" may contains special regex metacharacters, you will need to escape the siteNames items:
var siteNamesJoin = siteNames.map(function (x) { return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') }).join('|');
Also, if those words must match in between / or end of string, you may adjust the pattern:
var match = urlCurrent.match(new RegExp("^(.*?)/(?:(?:" + siteNamesJoin + ")(?![^/])|$)"));
See another demo.
var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.map(function (x) { return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') }).join('|');
var match = urlCurrent.match(new RegExp("^.*?/(?:(?:" + siteNamesJoin + ")(?![^/])|$)"));
var siteUrlCurrent = match ? match[0] : "";
console.log(siteUrlCurrent);
using regex & match
var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var regex = new RegExp(siteNames.join('|'));
var match = urlCurrent.match(regex);
if(match) {
var url = urlCurrent.substr(0, match[0].length + match.index)
console.log(url);
} else {
//invalid url
}
Maybe this helps you, i guess you don´t need a regex:
var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.join('|');
var siteUrlCurrent = urlCurrent.split(siteNamesJoin);
const pos = urlCurrent.split("/")[2];
let url;
for(const index in siteNames) {
if(pos === siteNames[index]) {
url = urlCurrent.substring(0,urlCurrent.lastIndexOf("/"));
}
}
console.log(url);

JavaScript Split, Split string by last DOT "."

JavaScript Split,
str = '123.2345.34' ,
expected output 123.2345 and 34
Str = 123,23.34.23
expected output 123,23.34 and 23
Goal : JS function to Split a string based on dot(from last) in O(n).
There may be n number of ,.(commas or dots) in string.
In order to split a string matching only the last character like described you need to use regex "lookahead".
This simple example works for your case:
var array = '123.2345.34'.split(/\.(?=[^\.]+$)/);
console.log(array);
Example with destructuring assignment (Ecmascript 2015)
const input = 'jquery.somePlugin.v1.6.3.js';
const [pluginName, fileExtension] = input.split(/\.(?=[^\.]+$)/);
console.log(pluginName, fileExtension);
However using either slice or substring with lastIndexOf also works, and albeit less elegant it's much faster:
var input = 'jquery.somePlugin.v1.6.3.js';
var period = input.lastIndexOf('.');
var pluginName = input.substring(0, period);
var fileExtension = input.substring(period + 1);
console.log(pluginName, fileExtension);
var str = "filename.to.split.pdf"
var arr = str.split("."); // Split the string using dot as separator
var lastVal = arr.pop(); // Get last element
var firstVal = arr.join("."); // Re-join the remaining substrings, using dot as separator
console.log(firstVal + " and " + lastVal); //Printing result
I will try something like bellow
var splitByLastDot = function(text) {
var index = text.lastIndexOf('.');
return [text.slice(0, index), text.slice(index + 1)]
}
console.log(splitByLastDot('123.2345.34'))
console.log(splitByLastDot('123,23.34.23'))
I came up with this:
var str = '123,23.34.23';
var result = str.replace(/\.([^.]+)$/, ':$1').split(':');
document.getElementById('output').innerHTML = JSON.stringify(result);
<div id="output"></div>
let returnFileIndex = str =>
str.split('.').pop();
Try this:
var str = '123.2345.34',
arr = str.split('.'),
output = arr.pop();
str = arr.join('.');
var test = 'filename.....png';
var lastStr = test.lastIndexOf(".");
var str = test.substring(lastStr + 1);
console.log(str);
I'm typically using this code and this works fine for me.
Jquery:
var afterDot = value.substr(value.lastIndexOf('_') + 1);
console.log(afterDot);
Javascript:
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
Note: Replace quoted string to your own need
My own version:
var mySplit;
var str1;
var str2;
$(function(){
mySplit = function(myString){
var lastPoint = myString.lastIndexOf(".");
str1 = myString.substring(0, lastPoint);
str2 = myString.substring(lastPoint + 1);
}
mySplit('123,23.34.23');
console.log(str1);
console.log(str2);
});
Working fiddle: https://jsfiddle.net/robertrozas/no01uya0/
Str = '123,23.34.23';
var a = Str.substring(0, Str.lastIndexOf(".")) //123,23.34
var b = Str.substring(Str.lastIndexOf(".")) //23
Try this solution.
Simple Spilt logic
<script type="text/javascript">
var str = "123,23.34.23";
var str_array = str.split(".");
for (var i=0;i<str_array.length;i++)
{
if (i == (str_array.length-1))
{
alert(str_array[i]);
}
}
</script>
The simplest way is mentioned below, you will get pdf as the output:
var str = "http://somedomain.com/dir/sd/test.pdf";
var ext = str.split('.')[str.split('.').length-1];
Output: pdf

Jquery - Add character after the first character of a string?

Say for example I have
var input = "C\\\\Program Files\\\\Need for Speed";
var output = do_it(input, ':');
Now, I would like output to have the value below :
C:\\\\Program Files\\\\Need for Speed
I need to add a character to the given string just after the first character. How can I achieve that using javascript or jquery ?
Thanks in advance
It's probably not the most efficient way, but I would do something like:
(note: this is just pseudocode)
var output = input[0] + ":" + input.substr(1, input.length);
you can use this like
String.prototype.addAt = function (index, character) {
return this.substr(0, index - 1) + character + this.substr(index-1 + character.length-1);
}
var input = "C\\Program Files\\Need for Speed";
var result = input.addAt(2, ':');
Heres one way of doing it:
Fiddle: http://jsfiddle.net/FjfB9/
var input = "C\\Program Files\\Need for Speed"
var do_it = function(str, char) {
var str = str.split(''),
temp = str.shift()
str.unshift(temp, char)
return str.join('')
}
console.log(do_it(input, ":"))

How do I escape a string used in a RegExp object

I have the following bit of code :
var stringToMatch = "De$mond. \(blah)";
var pattern = "^" + stringToMatch;
var regex = new RegExp(pattern, "i");
return regex.test("testing De$mond.");
Now I need to escape stringToMatch before using it in pattern
A solution I found here suggest this method if I understand correctly :
var stringToMatch = "De$mond. \(blah)";
stringToMatch = stringToMatch.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var pattern = "^" + stringToMatch;
var regex = new RegExp(pattern, "i");
return regex.test("testing De$mond.");
Why can't I simply escape all of the characters in stringToMatch instead?
e.g.
var stringToMatch = "De$mond. \(blah)";
var stringToMatchAsArrayOfChars = [];
for (var i = 0; i < stringToMatch.length; i++)
{
stringToMatchAsArrayOfChars.push(stringToMatch.substr(i, 1));
}
var stringToMatchEscaped = "";
for (var i = 0; i < stringToMatchAsArrayOfChars.length; i++)
{
if (stringToMatchAsArrayOfChars[i] !== " ")
{
stringToMatchEscaped = stringToMatchEscaped + "\\" + stringToMatchAsArrayOfChars[i];
}
else
{
stringToMatchEscaped = stringToMatchEscaped + " ";
}
}
var pattern = "^" + stringToMatch;
var regex = new RegExp(pattern, "i");
return regex.test("testing De$mond.");
I understand that the above method is much more verbose but what it basically does is :
var stringToMatchEscaped = "\D\e\$\m\o\n\d\. \\\(\b\l\a\h\)";
But it's not working. Why is that?
And, also, is there some other way of escaping stringToMatch other than the one suggested in the link I provided? i.e. without specifying which characters to escape like it's being dones with /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g ?
here is a simple regexp to make safe regexp patterns from string input.
var pattern= "De$mond.";
var regex = new RegExp(pattern.replace( /([.*+?^${}()|[\]\/\\])/g , '\\$1'), "i");
regex.test("testing De$mond. string here."); // === true
note that this means you cannot use the "wildcards" or any RegExp syntax, but you'll end up with a real regexp that will perform a literal match from the source text to the pattern.

Javascript regex help

I have the following string in JavaScript
var mystring = " abcdef(p,q); check(x,y); cef(m,n);"
I would want to do a string replace such that my final string is :
mystring = " abcdef(p,q); someothercheck\(x,y\); cef(m,n);"
x and y should remain same after the substitution. and the backslashes are necessary since I need to pass them to some other command.
There can be other Parantheses in the string too.
If you don't have other parenthesis, it should be easy.
mystring = mystring.replace("check(", "someothercheck\\(");
mystring = mystring.replace(")", "\\)");
EDIT This works also in the case of multiple parenthesis (It does not affect the empty ones).
var str=" abcdef; check(x,y); cef();"
patt = /((\w)/g;
// transform (x in \(x
str = str.replace(patt, '\\($1');
patt = /(\w)\)/g
// transform y) in y\);
str = str.replace(patt, '$1\\)');
// transform check in someothercheck
str = str.replace('check', 'someothercheck');
EDIT Now it converts only the check strings.
function convertCheck(str, check, someOtherCheck) {
// console.log(str + " contains " + check + "? ");
// console.log(str.indexOf(check));
if (str.indexOf(check) === -1) return str;
var patt1 = /\((\w)/g,
patt2 = /(\w)\)/g;
str = str.replace(patt1, '\\($1');
str = str.replace(patt2, '$1\\)');
str = str.replace(check, someOtherCheck);
return str;
}
var str = "abcdef(); check(x,y); cef();",
tokens = str.split(';');
for (var i = 0; i < tokens.length; i++) {
tokens[i] = convertCheck(tokens[i], "check", "someothercheck");
}
str = tokens.join(";");
alert(str); // "abcdef(); someothercheck/(x,y/); cef();"
var myString = "abcdef; check(x,y); cef;";
myString.replace(/(\w+)\(/, 'someother$1(')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')

Categories

Resources