Javascript regex help - javascript

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, '\\)')

Related

How to increment a string in JavaScript containing leading zeros?

I have string like:
MPG_0023
I want to find something like
MPG_0023 + 1
and I should get
MPG_0024
How to do that in JavaScript? It should take care that if there are no leading zeros, or one leading zero should still work like MPG23 should give MPG24 or MPG023 should give MPG024.
There should be no assumption that there is underscore or leading zeros, the only thing is that first part be any string or even no string and the number part may or may not have leading zeros and it is any kind of number so it should work for 0023 ( return 0024) or for gp031 ( return gp032) etc.
Here's a quick way without using regex.. as long as there's always a single underscore preceding the number and as long as the number is 4 digits, this will work.
var n = 'MPG_0023';
var a = n.split('_');
var r = a[0]+'_'+(("0000"+(++a[1])).substr(-4));
console.log(r);
Or if you do wanna do regex, the underscore won't matter.
var n = "MPG_0099";
var r = n.replace(/(\d+)/, (match)=>("0".repeat(4)+(++match)).substr(-4));
console.log(r);
You can use the regular expressions to make the changes as shown in the following code
var text = "MPG_0023";
var getPart = text.replace ( /[^\d.]/g, '' ); // returns 0023
var num = parseInt(getPart); // returns 23
var newVal = num+1; // returns 24
var reg = new RegExp(num); // create dynamic regexp
var newstring = text.replace ( reg, newVal ); // returns MPG_0024
console.log(num);
console.log(newVal);
console.log(reg);
console.log(newstring);
Using regex along with the function padStart
function add(str, n) {
return str.replace(/(\d+)/, function(match) {
var length = match.length;
var newValue = Number(match) + n;
return newValue.toString(10).padStart(length, "0");
});
}
console.log(add("MPG_023", 101));
console.log(add("MPG_0023", 101));
console.log(add("MPG_0000023", 10001));
console.log(add("MPG_0100023", 10001));
Using regular expression you can do it like this.
var text1 = 'MPG_0023';
var text2 = 'MPG_23';
var regex = /(.*_[0]*)(\d*)/;
var match1 = regex.exec(text1);
var match2 = regex.exec(text2);
var newText1 = match1[1] + (Number(match1[2]) + 1);
var newText2 = match2[1] + (Number(match2[2]) + 1);
console.log(newText1);
console.log(newText2);
Increment and pad the same value (comments inline)
var prefix = "MPG_"
var padDigit = 4; //number of total characters after prefix
var value = "MPG_0023";
console.log("currentValue ", value);
//method for padding
var fnPad = (str, padDigit) => (Array(padDigit + 1).join("0") + str).slice(-padDigit);
//method to get next value
var fnGetNextCounterValue = (value) => {
var num = value.substring(prefix.length); //extract num value
++num; //increment value
return prefix + fnPad(num, padDigit); //prepend prefix after padding
};
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
One way would e to split the string on the "_" character, increment the number and then add the zeros back to the number.
var testString = "MGP_0023";
var ary = testString.split("_");
var newNumber = Number(ary[1]) + 1;
var result = ary[0] + pad(newNumber);
// helper function to add zeros in front of the number
function pad(number) {
var str = number.toString();
while (str.length < 4) {
str = '0' + str;
}
return str;
}
You could cast to number, increment the value and cast back. Then check if you need leading zeros by looking at the length of the string.
Snippet below:
let str = "MPG_0023",
num = Number(str.substr(4)) + 1,
newStr = String(num);
function addLeading0(str) {
return str.length === 2 ? '00' + str : (str.length === 3 ? '0' + str : str);
}
console.log("MPG_" + addLeading0(newStr));

Find and Replace special char with defined value

I want to find and replace if a string contain /,+,?,-,_,# any of these into _sls_,_pls_,_wht_,_dsh_,_usc_,_hsh_ this respectively.
Example:
'_sls_'=>'/','_pls_'=>'+','_wht_'=>'?','_dsh_'=>'-','_usc_'=>'_','_hsh_'=>'#'
Mary_land = Mary_usc_land
Mary+land = Mary_pls_land
Write all the characters you want to get replaced into a function and call it
var string1 = "Mary_land";
var string2 = "Mary+lang";
var string3 = "Mary#lang";
var string4 = "Mary-lang";
var string5 = "Mary/lang?Maryland";
console.log(normalize(string1));
console.log(normalize(string2));
console.log(normalize(string3));
console.log(normalize(string4));
console.log(normalize(string5));
function normalize(str){
str = str.replace(/_/g,"_usc_");
str = str.replace(/\+/g,"_pls_");
str = str.replace(/\//g,"_sls_");
str = str.replace(/#/g,"_hsh_");
str = str.replace(/-/g,"_dsh_");
str = str.replace(/\?/g,"_wht_");
return str;
}

Remove all characters after the last special character javascript

I have the following string.
var string = "Welcome, to, this, site";
I would like to remove all characters after the last comma, so that the string becomes
var string = "Welcome, to, this";
How do I go about it in Javascript? I have tried,
var string = "Welcome, to, this, site";
string = s.substring(0, string.indexOf(','));
but this removes all characters after the first comma.
What you need is lastIndexOf:
string = s.substring(0, string.lastIndexOf('?'));
you can use split and splice to achieve the result as below.
var string = "Welcome, to, this, site";
string = string.split(',')
string.splice(-1) //Take out the last element of array
var output = string.join(',')
console.log(output) //"welcome, to, this"
There's a String.prototype.lastIndexOf(substring) method, you can just use that in replacement of String.prototype.indexOf(substring) :
var delimiter = ",";
if (inputString.includes(delimiter)) {
result = inputString.substring(0, inputString.lastIndexOf(delimiter));
} else {
result = inputString;
}
Alternatives would include Madara Uchiha's suggestion :
var delimiter = ",";
var parts = inputString.split(delimiter);
if(parts.length > 0) { parts.pop(); }
result = parts.join(delimiter);
Or the use of regular expressions :
result = inputString.replace(/,[^,]*$/, "");
Try this
var string = "Welcome, to, this, site";
var ss = string.split(",");
var newstr = "";
for(var i=0;i<ss.length-1;i++){
if (i == ss.length-2)
newstr += ss[i];
else
newstr += ss[i]+", ";
}
alert(newstr);

Random character in RegEx replace

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 + '<>');

How to get unmatched keywords?

I am using this as keyword s='young girl jumping'
function selfreplace(s) {
var words = ['man', 'jumping'];
var re = new RegExp('\\b(' + words.join('|') + ')\\b', 'g');
var specials = [];
var match;
var str = "";
while(match = re.exec(s)) {
str += match[0] + '(k)';
}
return str;
}
It is returning jumping(k)
I want the result to be young(s) girl(s) jumping(k)
It would probably be easiest to check if it's in words outside of the regex:
function selfreplace(s) {
var words = ['man','jumping'];
var re = new RegExp('\\b(\\w+)\\b', 'g');
var specials = [];
var match;
var str = "";
while(match = re.exec(s))
{
if (words.indexOf(match[0]) !== -1))
str += match[0] + '(k)';
else
str += match[0] + '(s)';
}
return str;
}
You can use a replace with callback.
function selfreplace(s){
return s.replace(/man|jumping|(\w+)/g, function(word, misc){
return word + (misc? '(s)' : '(k)')
})
}
If the word matched is man or jumping, only the first argument (entire match) is set. If the word matched is any other, the first capturing group is set as well.
If you don't know the set of words ahead, you can still generate the regex on the fly. Assuming words don't contain non-word characters:
function selfreplace(s, words){ //or any other method of passing 'words'
var re = RegExp(words.join("|")+"|(\\w+)",'g');
return s.replace(re, function(word, misc){
return word + (misc? '(s)' : '(k)')
})
}
Just a different approach, probably not the best solution but thought i'd throw it out there.
var str = "young girl jumping";
function replaceStr(s){
var matched = new RegExp("man|jumping", "i");
var newStr = "";
var str = s.split(" ");
for(var i=0; i<str.length;i++){
if(str[i].match(matched)){
newStr += str[i]+"(k) ";
} else {
newStr += str[i]+"(s) ";
}
}
return newStr.substr(0, newStr.length-1);
}
//replaceStr(str) returns "young(s) girl(s) jumping(k)"
DEMO here
if the matched words might change then you can always amend this function so it accepts an array as the second argument and then creates the regexp dynamically
replaceStr(s, matchArr){} and
var matched = new RegExp("("+matchArr.join("|")+")", "i");
Something like this might give you a hint:
var s = "young girl jumping",
words = ['man','jumping'],
regex = new RegExp("(" + words.join("|") +")", "g"),
q = s.replace(regex, function( string ) {
return string + "(k)";
});
console.log(q); // "young girl jumping(k)"
If you match words only, you do not really need regexps at all, do you?
What about just looking for the words with ==
function selfreplace(s) {
var words = ['man','jumping'];
var input = s.split(" ");
var str = "";
for(var i=0; i<input.length; i++){
var tmpString = "(s)";
for(var j=0; j<words.length; j++){
if(input[i] == words[j]){
tmpString = "(k)";
}
}
str += input[i]+tmpString;
}
return str;
}
You could use a RegExp for this, but for what you are doing a RegExp is overkill. I would use Array methods instead:
var selfreplace = function selfreplace(s) {
var words = ['man', 'jumping'],
i = 0,
suffix = '(s)';
s = s.split(' ');
for (i = 0; i < s.length; i += 1) {
if (words.indexOf(s[i]) > -1) {
s[i] = s[i] + '(k)';
} else {
s[i] = s[i] + '(s)';
}
}
return s.join(' ');
};
Here's a fiddle in action: http://jsfiddle.net/4KAzw/

Categories

Resources