Using Javascript RegExp object - javascript

I must have a syntax error in my code but I can't see it. fiddle here
var comma = ',,';
var stop = '.。';
var expression = '/[]+/';
expression = expression.substr(0,2) + comma + stop + expression.substr(2);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
}
I'm expecting res.length to be 3 but it is always 1 and returns the full string. What am I missing?

/ is used as delimiter for RegExp literal. e.g. /[a-zA-Z]/g
/ is not needed when you pass a pattern to the RegExp constructor. e.g. new RegExp('[a-zA-Z]', 'g')
To resolve the problem, remove the / (and modify the rest of your code):
var expression = '[]+';
Or you can just pass a RegExp literal directly:
var res = "foo,吧。baz".split(/[,,.。]+/g);

When you creat your Regex you're using this: var expression = '/[]+/';. The / delimiters are for use when you're delaring a regex like this:
var expression = /[]+/; // note: no quotes.
You're using new Regexp(), so they're not required in your string. Removing them gives this:
var comma = ',,';
var stop = '.。';
var expression = '[]+';
expression = expression.substr(0,1) + comma + stop + expression.substr(1);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
var item = document.createElement('li');
item.innerHTML = res[n];
document.getElementById('list').appendChild( item );
}
Which does what you expect. See this fiddle. I've adjusted the string indices and the loop index so that things work...

var expression = '/[]+/';
Should be
var expression = '[]+';
Also, adjust the substring indices accordingly
http://jsfiddle.net/2Pbm3/4/

Working like this :
var comma = ',,';
var stop = '.。';
var expression = '[]+';
expression = expression.substr(0,1) + comma + stop + expression.substr(1);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
var item = document.createElement('li');
item.innerHTML = res[n];
document.getElementById('list').appendChild( item );
}

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

I have to make a split function in JavaScript

Edit
sorry if the question wasn't clear
here is the question..
create your version of javascript split function,
you may use indexOf and substring to help.
so if i give you a string "heellloolllloolllo" and i want to remove "llll" the function should return "heellloooolllo"
This what I did so far:
function split() {
var entered_string = document.forms["form1"]["str"].value;
var deleted_char = document.forms["form1"]["char"].value;
var index = entered_string.indexOf(deleted_char);
var i = deleted_char.length;
var result;
var x ;
for (x = 0; x< entered_string.length; x++ )
{
if (index < 0) {
result = entered_string;
} else {
result = entered_string.substring(0, index) +entered_string.substring(index+i);
}
}
alert(result)
}
Use the replace() function with the g at the end of your regular expression. It's called a "global modifier".
var string = 'heellloolllloolllo';
var res = string.replace(/llll/g, '');
console.log(res)
If your substring is a variable then you need to construct a new Regex object and set the g as the second parameter.
var string = 'heellloolllloolllo';
var find = 'llll';
var regex = new RegExp(find,'g');
var res = string.replace(regex, '');
console.log(res)
There are other useful modifiers you can use:
g - Global replace. Replace all instances of the matched string in the provided text.
i - Case insensitive replace. Replace all instances of the matched string, ignoring differences in case.
m - Multi-line replace. The regular expression should be tested for matches over multiple lines.
See this post for more information, credit to #codejoe.
Using String#replace and RegExp (the clean way)
var str = 'llllheellloolllloolllollll';
var matchStr = 'llll';
function removeSubString(str, matchStr) {
var re = new RegExp(matchStr, 'g');
return str.replace(re,"");
}
console.log(removeSubString(str, matchStr));
Using String#indexOf and String#substring
var str = 'llllheellloolllloolllollll';
var matchStr = 'llll';
function removeSubString(str, matchStr) {
var index = str.indexOf(matchStr);
while(index != -1) {
var firstSubStr = str.substring(0, index);
var lastSubStr = str.substring(index + matchStr.length);
str = firstSubStr + lastSubStr;
index = str.indexOf(matchStr);
}
return str;
}
console.log(removeSubString(str,matchStr))

Split String after third slash

Consider the following string "/path1/path2/file.png".
Is it possible to extract "/path1/path2 through an regex? If so can you provide an example and how it works for it? If not what would be the alternative?
I would do it this way:
var str = '/path1/path2/file.png';
var regex = /(?:\/.*\/)(.*)/;
var filename = regex.exec(str)[1];
console.log(filename);
JSFiddle: https://jsfiddle.net/Ldpoqf0n/1/
this is another way without using regex:
var parts = str.split('/');
console.log(parts[parts.length - 1]);
let str = '"/path1/path2/file.png"';
console.log(str.replace(/\/\w+.\w+"/, ''));
Try this
const src = '/path1/path2/file.png'
const getFirstPart = src => (src.match(/\/.*?\/.*?(?=\/)/) || [])[0]
console.log(getFirstPart(src))
With regexes:
var path = "/path1/path2/file.png";
var patt = new RegExp("\/.*?\/[^\/]*");
var subpath = patt.exec(path)[0];
console.log(subpath)
Without regexes:
function getSubpath(path, subpathLevel) {
var arr = path.split("/");
var subpath = "";
for(var i = 0; i < subpathLevel && i < arr.length; i++)
subpath += "/" + arr[i+1];
return subpath;
}
console.log(getSubpath("/path1/path2/file.png", 2));
In subpathLevel variable you can set the quantity of slashes you want to consider (in the example is 2).

Select 2 characters after a particular substring in javascript

We have a string ,
var str = "Name=XYZ;State=TX;Phone=9422323233";
Here in the above string we need to fetch only the State value i.e TX. That is 2 characters after the substring State=
Can anyone help me implement it in javascript.
.split() the string into array and then find the index of the array element having State string. Using that index get to that element and again .split() it and get the result. Try this way,
var str = "Name=XYZ;State=TX;Phone=9422323233";
var strArr = str.split(';');
var index = 0;
for(var i = 0; i < strArr.length; i++){
if(strArr[i].match("State")){
index = i;
}
}
console.log(strArr[index].split('=')[1]);
jsFiddle
I guess the easiest way out is by slicing and splitting
var str = "Name=XYZ;State=TX;Phone=9422323233";
var findme = str.split(';')[1];
var last2 = findme.slice(-2);
alert(last2);
Need more help? Let me know
indexOf returns the position of the string in the other string.
Using this index you can find the next two characters
javascript something like
var n = str.indexOf("State=");
then use slice method
like
var res = str.slice(n,n+2);
another method is :
use split function
var newstring=str.split("State=");
then
var result=newstring.substr(0, 2);
Check this:
var str1 = "Name=XYZ;State=TX;Phone=9422323233";
var n = str1.search("State");
n=n+6;
var res = str1.substr(n, 2);
The result is in the variable res, no matter where State is in the original string.
There are any number of ways to get what you're after:
var str = "Name=XYZ;State=TX;Phone=9422323233"
Using match:
var match = str.match(/State=.{2}/);
var state = match? match[0].substring(6) : '';
console.log(state);
Using replace:
var state = str.replace(/^.*State=/,'').substring(0,2);
console.log(state);
Using split:
console.log(str.split('State=')[1].substring(0,2));
There are many other ways, including constructing an object that has name/value pairs:
var obj = {};
var b = str.split(';');
var c;
for (var i=b.length; i; ) {
c = b[--i].split('=');
obj[c[0]] = c[1];
}
console.log(obj.State);
Take your pick.

How to get parameter value inside a string?

Here's a thing i've been trying to resolve...
We've got some data from an ajax call and the result data is between other stuff a huge string with key:value data. For example:
"2R=OK|2M=2 row(s) found|V1=1,2|"
Is it posible for js to do something like:
var value = someFunction(str, param);
so if i search for "V1" parameter it will return "1,2"
I got this running on Sql server no sweat, but i'm struggling with js to parse the string.
So far i'm able to do this by a VERY rudimentary for loop like this:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
var arr = str.split("|");
var i = 0;
var value = "";
for(i = 0; i<arr.length; ++i){
if( arr[i].indexOf(param)>-1 ){
value = arr[i].split("=")[1];
}
}
console.log(value);
if i put that into a function it works, but i wonder if there's a more efficient way to do it, maybe some regex? but i suck at it. Hopefully somebody may shine a light on this for me?
Thanks!
This seems to work for your specific use-case:
function getValueByKey(haystack, needle) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp(needle + '=(.+)');
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1');
console.log(test);
JS Fiddle demo.
And, to include the separator in your search (in order to prevent somethingElseV1 matching for V1):
function getValueByKey(haystack, needle, separator) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp('\\' + separator + needle + '=(.+)\\' + separator);
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1', '|');
console.log(test);
JS Fiddle demo.
Note that this approach does require the use of the new RegExp() constructor (rather than creating a regex-literal using /.../) in order to pass variables into the regular expression.
Similarly, because we're using a string to create the regular expression within the constructor, we need to double-escape characters that require escaping (escaping first within the string and then escaping within in the created RegExp).
References:
RegExp.
String.match().
This should work for you and it's delimiters are configurable (if you wish to parse a similar string with different delimiters, you can just pass in the delimiters as arguments):
var parseKeyValue = (function(){
return function(str, search, keyDelim, valueDelim){
keyDelim = quote(keyDelim || '|');
valueDelim = quote(valueDelim || '=');
var regexp = new RegExp('(?:^|' + keyDelim + ')' + quote(search) + valueDelim + '(.*?)(?:' + keyDelim + '|$)');
var result = regexp.exec(str);
if(result && result.length > 1)
return result[1];
};
function quote(str){
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
})();
Quote function borrowed form this answer
Usage examples:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
parseKeyValue(str, param); // "1,2"
var str = "2R=OK&2M=2 row(s) found&V1=1,2";
var param = "2R";
parseKeyValue(str, param, '&'); // "OK"
var str =
"2R=>OK\n\
2M->2 row(s) found\n\
V1->1,2";
var param = "2M";
parseKeyValue(str, param, '\n', '->'); // "2 row(s) found"
Here is another approach:
HTML:
<div id="2R"></div>
<div id="2M"></div>
<div id="V1"></div>
Javascript:
function createDictionary(input) {
var splittedInput = input.split(/[=|]/),
kvpCount = Math.floor(splittedInput.length / 2),
i, key, value,
dictionary = {};
for (i = 0; i < kvpCount; i += 1) {
key = splittedInput[i * 2];
value = splittedInput[i * 2 + 1];
dictionary[key] = value;
}
return dictionary;
}
var input = "2R=OK|2M=2 row(s) found|V1=1,2|",
dictionary = createDictionary(input),
div2R = document.getElementById("2R"),
div2M = document.getElementById("2M"),
divV1 = document.getElementById("V1");
div2R.innerHTML = dictionary["2R"];
div2M.innerHTML = dictionary["2M"];
divV1.innerHTML = dictionary["V1"];
Result:
OK
2 row(s) found
1,2

Categories

Resources