replace string in json - javascript

I am new to javascript and have this code which will replace the string from A to B, but if there is multiple records of As, it will only replace the first A, while the remaining will be remain as A. Note that the stringify is called twice.
"success": function(json) {
var old = JSON.stringify(json).replace('"新交易"', '"待审核"');
var newdata = JSON.parse(old);
var old = JSON.stringify(newdata).replace('"批准"', '"已充值"');
var newdata = JSON.parse(old);
fnCallback(newdata);
}

This has little to do with JSON. As documented:
To perform a global search and replace, include the g switch in the regular expression.
So change this:
replace('"新交易"', '"待审核"')
... into this:
replace(/"新交易"/g, '"待审核"')

To replace every word in your context use Regular Expressions. So check this example to see how it works:
var someText = '"新交易""新交易""新交易""新交易""新交易""新交易""新交易""新交易"';
var someText2 = '"批准""批准""批准""批准""批准""批准""批准""批准""批准""批准"';
var old = someText.replace(/"新交易"/g, '"replaced"');
var stuff = someText2.replace(/"批准"/g, '"已充值"');
https://jsfiddle.net/n1otvpy1/

Related

String 'Regex' Validation for below scenario

var variables = ['A','B'];
var allowedMathFunc = ['Sin','Cos','Tan']
var expression= 'Sin(B)+Tan(B)+100+acos(A)+C'
I want to validate expression string match below scenario
expression should use variables array values
expression should not contain other then allowed math functions.
I tried below code
var variables = ['A','B'];
var allowedMathFunc = ['Sin','Cos','Tan']
var expression= 'Sin(B)+Tan(B)+100+acos(A)'
for variable check I tried this
let expressionVariables = value.replace(/Sin|Log|Exp|Tan|Pos|Rnd|[^A-Za-z]/ig,"");
let expressionUnUsedVar= variables.filter(v=> !expressionVariables.includes(v));
I don't know how to write for both scenario for regex it's not a problem for two different regex.
You can use regex to extract all variables and function names, and then check them if they're included in the allowed function and variable lists (case sensitive):
function testExpression(expression, vars, funcs) {
const usedVariables = expression.match(/\b[a-z]+\b(?!\s*\()/gi);
const usedFunctions = expression.match(/\b[a-z]+\b(?=\s*\()/gi);
return usedVariables?.every(v => vars.includes(v)) && usedFunctions?.every(func => funcs.includes(func));
}
var variables = ['A','B'];
var allowedMathFunc = ['Sin','Cos','Tan']
var expression= 'Sin(B)+Tan(B)+100+acos(A)+C'
console.log(testExpression(expression, variables, allowedMathFunc));
console.log(testExpression('Sin(B)+Tan(B)+100+Cos(A)+C', ['A','B','C'], ['Sin','Cos','Tan']));

Get all match values from two comma separated string

I have two comma separated string as follows,
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
I need to create another string based on the above two,
if hiddenString have unmatching value with strB,then without those unmatched values need to create e new string and also avoid duplicates.
simply says, I need to get all the matching values from both strings.
As the example based on my two string, I'm expecting the following:
varFinalHiddenString = 14172,10062,100;
How can I do this using JavaScript and that should work in safari and IE 11 or its earlier versions. Please help me, I'm new to the JS.
You can first split() strings to generate arrays from them. Then filter() the smaller array by checking the index of the current item with indexOf() in other array:
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
var temp1 = hiddenString.split(',');
var temp2 = strB.split(',');
var varFinalHiddenString = temp2.filter(function(s){
return temp1.indexOf(s) > -1;
}).join(',');
console.log(varFinalHiddenString);
Make arrays of the strings, then use the "filter" method. Then convert back to string.
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
var hiddenStringAsArray = hiddenString.split(',');
var strBArray = strB.split(',');
var resultObject = $(strBArray).filter(hiddenStringAsArray);
var resultArray = resultObject.toArray();
var resultString = resultArray.join(',');
console.log(resultString);

Javascript regexObj.exec() says TypeError: pattern.exec is not a function

I want to extract image name from img tag with regex in javascript. My problem is that console.log() throws Exception:TypeError: pattern.exec is not a function.
JS:
$("label.btn-danger").on('click',function(e){
e.preventDefault();
var src = $(this).parents("label").find("img").attr("src");
var pattern = "/\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/ig";
var result = pattern.exec(src)
console.log(result);
});
var pattern = "/\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/ig";
Creates a string. A string has no method exec. You meant a RegExp literal:
var pattern = /\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/ig;
I suppose you might as wel use the RegExp.test method here, if all you need is confirmation that src complies to the given pattern:
var result = /\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/ig.test(src);
If you need a matched value, use RegExp.match:
var result = src.match(/\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/ig);
// let src be '../images/someimage.png'
// then result[0] = '/someimage.png'

Convert string to become variable

I have multiple variables containing JSON as string (received from AJAX).
data.output_data_1234
data.output_data_5678
I convert them to Array:
var outputdataarr = new Array(data.output_data_1234);
This works fine, but how do I add a number to the var name:
var outputdataarr = new Array('data.output_data_'+formid+'');
this one does not work.
formid contains a proper number.
This does not work too:
var outputvar = window['data.output_data_' + formid];
var outputdataarr = new Array(outputvar);
Please help. Thanks.
You probably mean, you need something like this:
var outputdataarr = new Array(data['output_data_'+formid]);
You can only use string in square brackets as an object field identifier. It cannot contain '.'.
UPDATE:
However, you will probably need a loop to fill the whole array, e.g.
var outputdataarr = new Array();
for (var i=1000; i<2000; i++) {
outputdataarr.push(data['output_data_'+formid]);
}
Use [] instead of new Array is better.
var outputdataarr = [];
outputdataarr.push(data['output_data_'+formid]);
//and so on

How to do multiple regular expressions, each time refining the results?

Why can't I output my regex to a variable, and then run regex on it a second time?
I'm writing a greasemonkey javascript that grabs some raw data, runs some regex on it, then runs some more regex on it to refine the results:
// I tried this on :: http://stackoverflow.com/
var tagsraw = (document.getElementById("subheader").innerHTML);
alert(tagsraw);
Getting the raw data (above code) works
var trimone = tagsraw.match(/title\W\W\w+\s\w+\s\w+\s\w+\s\w+/g);
alert(trimone);
running regex once works (above code); but running (code below) doesn't??
var trimtwo = trimone.match(/\s\w+\s\w+\s\w+\s\w+/g);
alert(trimtwo);
Can some advise me as to what is wrong with my code/approach?
The reason the first match works, is because innerHTML returns a string.
However the match returns an array, thus treat it as one:
for (var i=0; i<trimone.length; i++)
{
var trimtwo = trimone[i].match(/\s\w+\s\w+\s\w+\s\w+/g);
alert(trimtwo);
}
Edit:
Try this code instead though, I think this is a bit closer to what you want to achieve:
var trimone = tagsraw.match(/title\s*=\s*".*"/g);
alert(trimone);
for (var i=0; i<trimone.length; i++)
{
alert(trimone[i]);
}
You could do something like this:
var str = "<title> foo bar baz quux blah</title>",
re = [
/title\W\W\w+\s\w+\s\w+\s\w+\s\w+/g,
/\s\w+\s\w+\s\w+\s\w+/g
],
tmp = [str];
for (var i=0, n=re.length; i<n; ++i) {
tmp = tmp.map(function(val) {
return val.match(re[i])[0];
});
}
alert(tmp);
.match should be returning an array, not a string.
Your case is better suited to using .exec. You could even chain the two if you don't care about the intermediate result:
/\s\w+\s\w+\s\w+\s\w+/g.exec(/title\W\W\w+\s\w+\s\w+\s\w+\s\w+/g.exec(tagsraw));
The problem is that match() returns an array and there is no built-in function to perform a regular expression on an array.
So instead you should be able to do this with the exec function from the Regexp object. It will return the matched string. You can grab the matched string from the first regexp and use it for the second.
So it'd be something like this:
var patt1 = new Regexp(/title\W\W\w+\s\w+\s\w+\s\w+\s\w+/g);
var trimone = patt1.exec(tagsraw);
if (trimone != null) // might be null if no match is found
{
alert(trimone);
var patt2 = new Regexp(/\s\w+\s\w+\s\w+\s\w+/g);
var trimtwo = patt2.exec(trimone);
alert(trimtwo);
}
Note that exec returns null if no match is found so be sure to handle that in your code like I do above.

Categories