Extract string from two identical symbols javascript - javascript

suppose I have a string :
I want to replace the above string as:
For this i tried as:
var result=[];
result=string.split("+");
console.log(result[1]);
It gives o/p: details.data
Now to replace the said part I tried as:
var res = string1.replace("+details.data+", ''+result[1]+'');
But it gives me o/p as: hello someting "+details.data+" still something
I want to replace exactly in the attachment.
Is there any other way to achieve this?

Can't you use: str.replace("+details.data+", `\`+${result[1]}+\``) ?
This way you are replacing the string with a template literal which includes the result (evaluated to a string). It also includes the backticks in the string by escaping them with backslashes.

I believe what you're trying to achieve is this:
let string1 = "hello something +details.data+ hello something";
const result = ['data', 'yay! My data is here'];
const updatedString = string1.replace('+details.data+', `+${result[1]}+`);
console.log(updatedString);
By using a template literal we can easily replace the details.data with the result data.

Assuming that you want to replace +details.data+ with the actual value of details.data
You need something like this:
var details = { data: 'blabla' }
const string = `hello something "+details.data+" still something`;
string = string.replace('+details.data+', details.data);
console.log(string); // hello something "blabla" still something
If you wanted this to be dynamic you would need the details object as a prop of another object:
var obj = { details: { data: 'blabla' }}
var arr = string.split('+'); // ['hello something "','details.data','" still something']
var path = arr[1].split('.'); // ['details', 'data']
// you would need some logic here to check that each of the props from path exists in obj
var value = obj[path[0]][path[1]];
string = string.replace('+details.data+', value);
console.log(string);

Related

How change a string looks like array to a real aray

I have a string, it looks like a array but not a real array. So my question is how to make it to a real array.
let string = "["abc", "cde"]";
// how to make string become an array
change string to an array
First you need to make sure your string is invalid format
"["abc", "cde"]" // invalid
"[abc, cde]" // invalid
"[11, 22]" // valid,if you do not want to use quote to wrap it,then the elements need to be number
"['abc', 'cde']" // valid
let string = `["abc", "cde"]`
const array = JSON.parse(string)
console.log(array)
You can do something like this
let data = "['abc', 'pqr', 'xxx']";
data = data.replace(/'/g, '"');
console.log(data)
const convertedArray = JSON.parse(data);
console.log(convertedArray)
Observation : Your input string is not a valid JSON string.
Solution : Double quotes besides the array items should be escaped to parse it properly. Your final string should be.
let string = "[\"abc\", \"cde\"]";
Now you can parse it using JSON.parse() method.
Live Demo :
let string = "['abc', 'cde']";
string = string.replace(/'/g, '"');
console.log(string); // "[\"abc\", \"cde\"]"
console.log(JSON.parse(string)); // ["abc", "cde"]

Part of the string is missing when trying to replace

I have a string that looks like this:
[TITLE|prefix=X|suffix=a] [STORENAME|prefix=b] [DYNAMIC|limit=10|seperator=-|random=1|reverse=1|prefix=c]
I would like to replace the values of all prefix attributes with hello. So the goal is that the string looks like this:
[TITLE|prefix=hello|suffix=a] [STORENAME|prefix=hello] [DYNAMIC|limit=10|seperator=-|random=1|reverse=1|prefix=hello]
This is what I have tried:
const obj = {};
obj.prefix = "[TITLE|prefix=a|suffix=x] [STORENAME|prefix=b] [DYNAMIC|limit=10|seperator=-|random=1|reverse=1|prefix=c]";
function replace(search, replace) {
const regex = new RegExp(`(?<=\\[${search}\\|[^\\]]*${replace}=)[^|\\]]+`);
obj.prefix = obj.prefix.replace(regex, 'hello');
}
replace('TITLE', 'prefix');
replace('STORENAME', 'prefix');
replace('DYNAMIC', 'prefix');
console.log(obj.prefix);
As you see it works fine!
I have used almost the same code for my project but it fails. You can check my project on JSFiddle. Just type anything on an input field and check the console. You will see that the value of first prefix will be changed but 2 further prefix attributes are missing.
So this is what I get:
[TITLE|prefix=anything|suffix=a] [STORENAME] [DYNAMIC|limit=10|seperator=-|random=1|reverse=1]
And this is what I should get:
[TITLE|prefix=anything|suffix=a] [STORENAME|prefix=another thing] [DYNAMIC|limit=10|seperator=-|random=1|reverse=1|prefix=one more thing]
What is the reason that those attributes are missing?
Update
If I am not mistaking, my main problem is the if-statement:
if (mtPr.query[mtPr.settings.activeLang].includes(replace)) {
With this if-statement, I would like to check if either TITLE has the attribute prefix or STORENAME has the attribute prefix or DYNAMIC has the attribute prefix. But this is a bad workaround since the value of replace is always prefix (see line numbers 241, 245 and 251). And since we already have prefix in the WHOLE string, it means that we're caught in that if-statement every single time. So a possible solution could be, checking if the parameter replace is included AND does it belong to the parameter search.
Try this
function replace(search, replace) {
const regex = new RegExp(`(${search}[^\\[\\]]*\\|prefix\\=)[^\\|\\[\\]]+`);
obj.prefix = obj.prefix.replace(regex, '$1hello');
}
As I have described in my question, the problem was really the if-statement. This how I could resolve it:
const searchMatchesReplace = new RegExp(`(?<=${search}.+${replace}=)[^\\]|]+`);
if (searchMatchesReplace.test(mtPr.query[mtPr.settings.activeLang])) {
const regex = new RegExp(`(?<=\\[${search}\\|[^\\]]*${replace}=)[^|\\]]+`, 'g');
result = mtPr.query[mtPr.settings.activeLang].replace(regex, value);
}
// Replace parameters if they do not exist
else {
const regex = new RegExp(`(\\[${search}(?:\\|[^\\][]*)?)]`, 'gi');
result = mtPr.query[mtPr.settings.activeLang].replace(regex, `$1|${replace}=${value}]`);
}

How to get parameterise a string separated by commas with regex?

I have a string that looks like this:
{{tagName(21, 'hello, jane','smith')}}
I'm trying to use regex to match() this string to result in:
[0] = tagName
[1] = 21
[2] = 'hello, jane'
[3] = 'smith'
The parameter part of the string can grow. That is to say, it may have more or less parameters and the regex needs to be "greedy" yet knows how to group them up.
I've been trying something like that: ^\{\{([^\(]+)\({1}(.*)\){1}\}\}
But this results in:
[0] = tagName
[1] = 21, 'hello, jane','smith'
What should I do to my regex to get the results I want?
Replace {, }, (, ) with empty string; match [a-z]+, \d+, '.+' followed by , or end of input
var str = "{{tagName(21, 'hello, jane','smith')}}";
var res = str.replace(/\{|\}|\(|\)/g, "")
.match(/([a-z]+)|\d+|('.+')(?=,)|('.+')(?=$)/ig);
console.log(res);
If you're ok with using two regexes, you can return a new array with function name and concat all the parameters onto that array.
With ES6 you can use the spread operator:
const str = "{{tagName(21, 'hello, jane','smith')}}";
const result = str.match(/^\{\{([^\(]+)\({1}(.*)\){1}\}\}/);
console.log([
result[1],
...result[2].match(/^\d+|'.*?'/g)
])
In ES5 you'll have to concat the parameters onto the array containing the function name as its first item:
var str = "{{tagName(21, 'hello, jane','smith')}}";
var result = str.match(/^\{\{([^\(]+)\({1}(.*)\){1}\}\}/);
console.log([result[1]].concat(result[2].match(/^\d+|'.*?'/g)))
In reality, you could concat in ES6, but
So far I've manage to come up with the following:
([A-Za-z]+)|('.*?'|[^',\s\(]+)(?=\s*,|\s*\))
Tested on https://regex101.com

javascript retrieve value from JSON object by matching key using Regex

I have the following javascript object literal (excerpt)
var foo = {"hello[35]":100,"goodbye[45]":42};
I have the following query:
var query = "hello"
I would like to call foo[query] to obtain the value 100, but there is a [35] for which I don't necessarily know the value of. I know for sure that I will get a unique match. Is there any way to input query is some kind of javascript regular expression? i.e.
Regex = /hello/
foo[Regex]
100
pardon the noob question...
What you have here:
var foo = {"hello[35]":100,"goodbye[45]":42};
is not JSON, which is a string representation of an object; what you have is an object literal, which creates an actual JavaScript object. As far as I know the only way to retrieve a value from an object by matching a property name with a regex is to enumerate the property names and test each one. The regex you'll need is something like:
/^hello(\[\d*\])?$/
...which will match against "hello" optionally followed by zero or more digits in square brackets. But you don't want to hard code "hello" given that you also (presumably) need the "goodbye" value, so use a function:
function getPropertyByRegex(obj,propName) {
var re = new RegExp("^" + propName + "(\\[\\d*\\])?$"),
key;
for (key in obj)
if (re.test(key))
return obj[key];
return null; // put your default "not found" return value here
}
var foo = {"hello[35]":100,"goodbye[45]":42};
alert(getPropertyByRegex(foo, "hello")); // 100
alert(getPropertyByRegex(foo, "goodbye")); // 42
alert(getPropertyByRegex(foo, "whatever")); // null (not found)
Demo: http://jsfiddle.net/asDQm/
Not sure if you can use regex without any plugins or so ...
This might help already ...
var foo = {"hello[35]":100,"goodbye[45]":42};
var query = "hello";
for(var key in foo){
if (key.indexOf(query) > -1)
document.write(foo[key]);
}
http://jsfiddle.net/3qqSr
I am noob here too but I have seen this page previously see it helps you with your question. It basically explains JSon path. Also see this question.
As your JSON is a string, you can use a regexp with this kind of statement:
var foo = '{"hello[35]":100,"goodbye[45]":42}';
var result = foo.match(/"hello\[\d*\]":\d*/g);
result = result[0].split(":")[1];
alert(result);
See it live on jsfiddle
Note that you could use a var instead of "hello" in your regexp.
var foo = {"hello[35]":100,"goodbye[45]":42};
foo = foo.replace(/\[\d+\]/g,'');
var obj = (new Function("return "+foo))();
obj.hello -> 100
obj.goodbye -> 42
var query = 'hello';
obj[query] -> 100
function getVal(s, q){
var r = s.match(new RegExp(q + "\\[\\d*\\]\":(\\d*)[\\,\\}]"));
return r?r.pop():false;
}
getVal(foo, "hello")

Does javascript have a method to replace part of a string without creating a new string?

var str = "This is a string";
var thing = str.replace("string","thing");
console.log( str )
>> "This is a string"
console.log( thing )
>> "This is a thing"
Is there another method I can use, besides replace, that will alter the string in place without giving me a new string object?
No, strings in JavaScript are immutable.
Not that i am aware of, however if the reason you want to do this is just to keep your code clean you can just assign the new string the the old variable:
var string = "This is a string";
string = string.replace("string", "thing");
Of course this will just make the code look a bit cleaner and still create a new string.
There is a reason why strings are immutable. As Javascript use call-by-sharing technic, mutable string would be a problem in this case :
function thinger(str) {
return str.replace("string", "thing");
}
var str = "This is a str";
var thing = thinger(str);
In this situation you want your string to be passed by value, but it is not. If str was mutable, thinger would change str, that would be a really strange effect.
As Cristian Sanchez mentioned, in javascript strings are immutable.
Depending on the task we can try to work around with the following approaches:
// **fastest** .split(...).join(...)
var string = 'My string'
string = string.split('string').join('thing')
console.info('with .split-.join', { string }) // 'My thing'
// **good old wine** .replace('...','...') as mentioned above
string = 'My string'
string = string.replace('string','thing')
console.info('with .replace', { string }) // 'My thing'
// **ES6 string interpolation**
string = (arg) => `My ${arg}`
console.info('with interpolation 1', { string: string('string') }) // 'My string'
console.info('with interpolation 2', { string: string('thing') }) // 'My thing'
Note: there are fancy ways with such approaches as ..indexOf(...) and .substring(...), .charAt(...),

Categories

Resources