converting a string to stringified JSON - javascript

I'm getting a string which looks like following
"{option:{name:angshu,title:guha}}"
Now I have to make a valid JSON string from this. Is there any smart way to convert that. I tried with string handelling but that takes a lot of conditions still being case specific. Even i tried with eval() that doesn't work also.

This regex will do the trick for the provided example string:
/:([^{},]+)/g
Regex101 analysis of it:
: matches the character : literally
1st Capturing group ([^{},]+)
[^{,}]+ match a single character not present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
{}, a single character in the list {}, literally
g modifier: global. All matches (don't return on first match)
Basically, it looks for all characters following a : that aren't {},. those "words" are saved in the 1st capturing group, which allows .replace to re-use them with $1.
You can use the regex like this:
var raw = "{option:{name:angshu,title:guha}}",
regex = /:([^{,}]+)/g,
replacement = ':"$1"';
var jsonString = raw.replace(regex, replacement);
alert(jsonString);

try this if you are looking for JSON object
string inputString = '{option:{name:angshu,title:guha}}';
var obj = JSON.parse(inputString);

Related

Split a string in two, keeping words intact and returning them

As the title says, looking to see how I can split a string into two parts, while keeping full words intact, and having access to both parts with JavaScript. I am using this string in a pug file.
For instance, I have a very long string
let str = `hello i am a very long string that needs to be split into two different parts! thank you so much for helping.'
I want the first 70 characters, to use as a headline, then the rest to use for the body of the element.
I have used this regex that I found on an older post that gives me the first 70+ characters, with full words...
str.replace(/^([\s\S]{70}[^\s]*)[\s\S]*/, "$1")
which does what I want it to do! But now I need to figure out if there is a way to get the rest of that string?
str1 = `hello i am a very long string that needs to be split into two different`
str2 = `parts! thank you so much for helping.`
Again, using this in a pug file, so if there is a simple answer, I would love that. Otherwise I suppose I could just write a function and import the script to the pug view.
What would you want to do when the split happens on a whitespace character. Say; the space right after 'different'. It would mean that the part prior to the space is 69 characters, but 70 if you'd include the space. Assuming you want to capture the next word for good measure, try to utilize JS's zero-width lookbehind:
(?<=^.{70}\S*)\s+
See an online demo
(?<= - Open positive lookbehind;
^.{70} - 70 Characters right after start-line anchor;
\S* - 0+ Non-whitespace chars;
\s+ - Capture 1+ whitespace characters to split on.
const str = 'hello i am a very long string that needs to be split into two different parts! thank you so much for helping';
const result = str.split(/(?<=^.{70}(?:\S)*)\s+/);
console.log(result);
After extracting the first part of the string using your method you can use the length of str1 to determine where in str the second part begins. From there you can use substring to extract it.
let str = `hello i am a very long string that needs to be split into two different parts! thank you so much for helping.`;
let str1 = str.replace(/^([\s\S]{70}[^\s]*)[\s\S]*/, "$1");
let str2 = str.substring(str1.length).trimStart();
Using trimStart you can to remove any whitespace that would appear at the start of str2.
If you instead just take a look at the matches:
const matches = str.match(/^([\s\S]{70}[^\s]*)[\s\S](.*)/);
You will see the second match contains your header text and the third match your body text.
An alternative solution to the previous one, but using only regex would be the following:
let listStrings = str.split(/^([\s\S]{70}[^\s]*)[\s\S](.*)/)).filter(Boolean)
I added to your regex the last part (.*) to obtain the rest of the string as another group. Then, using the javascript string split function you can apply the regex and get a list of strings, being those the groups obtained by the regex.
The .filter(Boolean) is used to remove the empty strings obtained in the response:
0:""
1:"hello i am a very long string that needs to be split into two different"
2:"parts! thank you so much for helping."
3:""

Javascript: Remove trailing chars from string if they are non-numeric

I am passing codes to an API. These codes are alphanumeric, like this one: M84.534D
I just found out that the API does not use the trailing letters. In other words, the API is expecting M84.534, no letter D at the end.
The problem I am having is that the format is not the same for the codes.
I may have M84.534DAC, or M84.534.
What I need to accomplish before sending the code is to remove any non-numeric characters from the end of the code, so in the examples:
M84.534D -> I need to pass M84.534
M84.534DAC -> I also need to pass M84.534
Is there any function or regex that will do that?
Thank you in advance to all.
You can use the regex below. It will remove anything from the end of the string that is not a number
let code = 'M84.534DAC'
console.log(code.replace(/[^0-9]+?$/, ""));
[^0-9] matches anything that is not a numer
+? Will match between 1 and unlimited times
$ Will match the end of the string
So linked together, it will match any non numbers at the end of the string, and replace them with nothing.
You could use the following expression:
\D*$
As in:
var somestring = "M84.534D".replace(/\D*$/, '');
console.log(somestring);
Explanation:
\D stands for not \d, the star * means zero or more times (greedily) and the $ anchors the expression to the end of the string.
Given your limited data sample, this simple regular expression does the trick. You just replace the match with an empty string.
I've used document.write just so we can see the results. You use this whatever way you want.
var testData = [
'M84.534D',
'M84.534DAC'
]
regex = /\D+$/
testData.forEach((item) => {
var cleanValue = item.replace(regex, '')
document.write(cleanValue + '<br>')
})
RegEx breakdown:
\D = Anything that's not a digit
+ = One or more occurrences
$ = End of line/input

JavaScript RegExp all chracters except dynamic series

So, I'm working on an opensource project as a way to expand my knowledge of JavaScript, and created an utility that processes strings dynamically, and replaces specific occurrences with other strings.
An example of this would be the following:
jdhfkjhs${c1}kdfjh$%^%$S654sgdsjh${c20}SUYTDRF^%$&*#(Y
And assuming I select the character '#', the RegExp processes it to be:
########${c1}####################${c20}###############
The problem I am facing is my RegExp /[^\$\{c\d\}]/g is also matching any of the characters inside of the RegExp, so a string such as _,met$$$$$1234{}cccgg. will be returned as #####$$$$$1234{}ccc###
Is there a way I can catch such a dynamic group with JavaScript, or should I find an alternative way to achieve what I am doing?
For some context, the project code can be found here.
You may match the group and capture it to restore later, and just match any char (with . if no line breaks are expected or with [^] / [\s\S]):
var rx = /(\${c\d+})|./g;
var str = 'jdhfkjhs\${c1}kdfjh\$%^%\$S654sgdsjh\${c20}SUYTDRF^%\$&*#(Y';
var result = str.replace(rx, function ($0,$1) {
return $1 ? $1 : '#';
});
console.log(result);
Details:
(\${c\d+}) - Group 1: a literal ${c substring, then 1+ digits and a literal }
| - or
. - any char but a line break char (or any char if you use [^] or [\s\S]).
In the replacement, $0 stands for the whole match, $1 stands for the contents of the first capturing group. If the $1 is set, it is re-inserted to the resulting string, else, the char is replaced with #.

Regex match for a specific pattern excluding a specific pattern

I have sample string as :
'&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89&color=ff0000|00ffff'
'&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89'
My objective is to select the text from 'tooltext=' till the first occurrence of '&' which is not preceded by \\. I'm using the following regex :
/(tooltext=)(.*)([^\\])(&)/
and the .match() function.
It is working fine for the second string but for the first string it is selecting upto the last occurrence of '&' not preceded by \\.
var a = '&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89&color=ff0000|00ffff',
b = a.match(/(tooltext=)(.*)([^\\])(&)(.*[^\\]&)?/i)
result,
b = ["tooltext=abc\&|\|cba&value=40|84|40|62&", "tooltext=", "abc\&|\|cba&value=40|84|40|6", "2", "&"]
But what i need is:
b = ["tooltext=abc&||cba&", "tooltext=", "abc&||cb", "a", "&"]
I think you can use a regex like this:
/tooltext=(.*?\\&)*.*?&/
[Regex Demo]
and to always found a non-escaped &:
/tooltext=(.*?\\&)*.*?[^\\]&/
It looks like your regex is matching all the way to the last & instead of the first one without a backslash in front of it. Try adding the ? operator to make it match as small as possible like so:
/(tooltext=)(.*?)([^\\])(&)/
And if you just want the text between tooltext= and &, try this to make it return the important part as the matched group:
/tooltext=(.*?[^\\])&/

javascript regex to return letters only

My string can be something like A01, B02, C03, possibly AA18 in the future as well. I thought I could use a regex to get just the letters and work on my regex since I haven't done much with it. I wrote this function:
function rowOffset(sequence) {
console.log(sequence);
var matches = /^[a-zA-Z]+$/.exec(sequence);
console.log(matches);
var letter = matches[0].toUpperCase();
return letter;
}
var x = "A01";
console.log(rowOffset(x));
My matches continue to be null. Am I doing this correctly? Looking at this post, I thought the regex was correct: Regular expression for only characters a-z, A-Z
You can use String#replace to remove all non letters from input string:
var r = 'AA18'.replace(/[^a-zA-Z]+/g, '');
//=> "AA"
Your main issue is the use of the ^ and $ characters in the regex pattern. ^ indicates the beginning of the string and $ indicates the end, so you pattern is looking for a string that is ONLY a group of one or more letters, from the beginning to the end of the string.
Additionally, if you want to get each individual instance of the letters, you want to include the "global" indicator (g) at the end of your regex pattern: /[a-zA-Z]+/g. Leaving that out means that it will only find the first instance of the pattern and then stop searching . . . adding it will match all instances.
Those two updates should get you going.
EDIT:
Also, you may want to use match() rather than exec(). If you have a string of multiple values (e.g., "A01, B02, C03, AA18"), match() will return them all in an array, whereas, exec() will only match the first one. If it is only ever one value, then exec() will be fine (and you also wouldn't need the "global" flag).
If you want to use match(), you need to change your code order just a bit to:
var matches = sequence.match(/[a-zA-Z]+/g);
To return an array of separate letters remove +:
var matches = sequence.match(/[a-zA-Z]/g);
You're confused about what the goal of the other question was: he wanted to check that there were only letters in his string.
You need to remove the anchors ^$, who match respectively the beginning and end of the string:
[a-zA-Z]+
This will match the first of letters in your input string.
If there might be more (ie you want multiple matches in your single string), use
sequence.match(/[a-zA-Z]+/g)
This /[^a-z]/g solves the problem. Look at the example below.
function pangram(str) {
let regExp = /[^a-z]/g;
let letters = str.toLowerCase().replace(regExp, '');
document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2## %hfr efg uor7 489(*&^% knt lhtkjj ngnm!##$%^&*()_');
<h4 id="letters"></h4>
You can do this:
var r = 'AA18'.replace(/[\W\d_]/g, ''); // AA
Also can be done by String.prototype.split(regex).
'AA12BB34'.split(/(\d+)/); // ["AA", "12", "BB", "34", ""]
'AA12BB34'.split(/(\d+)/)[0]; // "AA"
Here regex divides the giving string by digits (\d+)

Categories

Resources