I am trying to extract a component name from a string so I can parse the rest with JSON and also return the component name.
Let's say I have a string as follows:
namespace/Slider {"showCaptions":true,"circular":false,"autoPlay":true,"showItemNavigators":true,"showItemNavigatorsOnHover":true,"showIndicators":false,"indicatorsPosition":"bottom","showThumbnails":true,"numVisible":10,"numVisible1536":8,"numVisible1280":6,"numVisible1024":4,"numVisible768":3,"numVisible640":2,"changeItemOnIndicatorHover":false,"images":[{"id":1701,"url":"http://localhost:10019/wp-content/uploads/2022/12/horse.jpeg","alt":"horse alt","caption":"Name some name"},{"id":1699,"url":"http://localhost:10019/wp-content/uploads/2022/12/GPJNews_Mongolia_KK_RidingChild_076_web-920x613-1.jpeg","alt":"","caption":"Name GP"},{"id":1238,"url":"http://localhost:10019/wp-content/uploads/2022/08/test-scaled.jpeg","alt":"","caption":""},{"id":458,"url":"http://localhost:10019/wp-content/uploads/2022/09/news-scaled-1.jpeg","alt":"","caption":"Paswan a mother who..."}]}
I want to remove the "namespace/Slider" part from the string and return the rest so I can JSON.parse it and also want to return "Slider" so the part after namespace as a variable.
EDIT: This is how I was doing it before and it worked until I had a ( in any of the fields eg: "caption":"(Name GP"
const str = `namespace/Slider {"showCaptions":true,"circular":false,"autoPlay":true,"showItemNavigators":true,"showItemNavigatorsOnHover":true,"showIndicators":false,"indicatorsPosition":"bottom","showThumbnails":true,"numVisible":10,"numVisible1536":8,"numVisible1280":6,"numVisible1024":4,"numVisible768":3,"numVisible640":2,"changeItemOnIndicatorHover":false,"images":[{"id":1701,"url":"http://localhost:10019/wp-content/uploads/2022/12/horse.jpeg","alt":"horse alt","caption":"Name some name"},{"id":1699,"url":"http://localhost:10019/wp-content/uploads/2022/12/GPJNews_Mongolia_KK_RidingChild_076_web-920x613-1.jpeg","alt":"","caption":"Name GP"},{"id":1238,"url":"http://localhost:10019/wp-content/uploads/2022/08/test-scaled.jpeg","alt":"","caption":""},{"id":458,"url":"http://localhost:10019/wp-content/uploads/2022/09/news-scaled-1.jpeg","alt":"","caption":"Paswan a mother who..."}]}`;
const component = str
.replace(/\{([^()]|())*\}/gi, '')
.trim()
.split('/')[1];
const obj = str.match(/\{([^()]|())*\}/gi)[0]
console.log(component, obj);
Take the substring starting from the first { character.
let str = 'namespace/Slider {"showCaptions":true,"circular":false,"autoPlay":true,"showItemNavigators":true,"showItemNavigatorsOnHover":true,"showIndicators":false,"indicatorsPosition":"bottom","showThumbnails":true,"numVisible":10,"numVisible1536":8,"numVisible1280":6,"numVisible1024":4,"numVisible768":3,"numVisible640":2,"changeItemOnIndicatorHover":false,"images":[{"id":1701,"url":"http://localhost:10019/wp-content/uploads/2022/12/horse.jpeg","alt":"horse alt","caption":"Name some name"},{"id":1699,"url":"http://localhost:10019/wp-content/uploads/2022/12/GPJNews_Mongolia_KK_RidingChild_076_web-920x613-1.jpeg","alt":"","caption":"Name GP"},{"id":1238,"url":"http://localhost:10019/wp-content/uploads/2022/08/test-scaled.jpeg","alt":"","caption":""},{"id":458,"url":"http://localhost:10019/wp-content/uploads/2022/09/news-scaled-1.jpeg","alt":"","caption":"Paswan a mother who..."}]}';
let idx = str.indexOf('{');
console.log(str.slice(str.indexOf('/') + 1, idx));
console.log(JSON.parse(str.slice(idx)));
This example uses replace(), sub-expressions (sub-expression) and back-references $number:
let str = 'namespace/Slider {"showCaptions":true,"circular":false,"autoPlay":true,"showItemNavigators":true,"showItemNavigatorsOnHover":true,"showIndicators":false,"indicatorsPosition":"bottom","showThumbnails":true,"numVisible":10,"numVisible1536":8,"numVisible1280":6,"numVisible1024":4,"numVisible768":3,"numVisible640":2,"changeItemOnIndicatorHover":false,"images":[{"id":1701,"url":"http://localhost:10019/wp-content/uploads/2022/12/horse.jpeg","alt":"horse alt","caption":"Name some name"},{"id":1699,"url":"http://localhost:10019/wp-content/uploads/2022/12/GPJNews_Mongolia_KK_RidingChild_076_web-920x613-1.jpeg","alt":"","caption":"Name GP"},{"id":1238,"url":"http://localhost:10019/wp-content/uploads/2022/08/test-scaled.jpeg","alt":"","caption":""},{"id":458,"url":"http://localhost:10019/wp-content/uploads/2022/09/news-scaled-1.jpeg","alt":"","caption":"Paswan a mother who..."}]}';
let name = str.replace(/(namespace)\/(\w+)\s+(\{.+\})/, "$2") // Slider
let json = str.replace(/(namespace)\/(\w+)\s+(\{.+\})/, "$3") // {...}
The same example example uses match() and sub-expressions (sub-expression):
let str = 'namespace/Slider {"showCaptions":true,"circular":false,"autoPlay":true,"showItemNavigators":true,"showItemNavigatorsOnHover":true,"showIndicators":false,"indicatorsPosition":"bottom","showThumbnails":true,"numVisible":10,"numVisible1536":8,"numVisible1280":6,"numVisible1024":4,"numVisible768":3,"numVisible640":2,"changeItemOnIndicatorHover":false,"images":[{"id":1701,"url":"http://localhost:10019/wp-content/uploads/2022/12/horse.jpeg","alt":"horse alt","caption":"Name some name"},{"id":1699,"url":"http://localhost:10019/wp-content/uploads/2022/12/GPJNews_Mongolia_KK_RidingChild_076_web-920x613-1.jpeg","alt":"","caption":"Name GP"},{"id":1238,"url":"http://localhost:10019/wp-content/uploads/2022/08/test-scaled.jpeg","alt":"","caption":""},{"id":458,"url":"http://localhost:10019/wp-content/uploads/2022/09/news-scaled-1.jpeg","alt":"","caption":"Paswan a mother who..."}]}';
let matches = str.match(/(namespace)\/(\w+)\s+(\{.+\})/)
let name = matches[2] // Slider
let json = matches[3] // {...}
Using regex match and destructuring to get the relevant parts
const str = `namespace/Slider {"showCaptions":true,"circular":false,"autoPlay":true,"showItemNavigators":true,"showItemNavigatorsOnHover":true,"showIndicators":false,"indicatorsPosition":"bottom","showThumbnails":true,"numVisible":10,"numVisible1536":8,"numVisible1280":6,"numVisible1024":4,"numVisible768":3,"numVisible640":2,"changeItemOnIndicatorHover":false,"images":[{"id":1701,"url":"http://localhost:10019/wp-content/uploads/2022/12/horse.jpeg","alt":"horse alt","caption":"Name some name"},{"id":1699,"url":"http://localhost:10019/wp-content/uploads/2022/12/GPJNews_Mongolia_KK_RidingChild_076_web-920x613-1.jpeg","alt":"","caption":"Name GP"},{"id":1238,"url":"http://localhost:10019/wp-content/uploads/2022/08/test-scaled.jpeg","alt":"","caption":""},{"id":458,"url":"http://localhost:10019/wp-content/uploads/2022/09/news-scaled-1.jpeg","alt":"","caption":"Paswan a mother who..."}]}`
const [_,namespace,jsonString] = str.match(/^\w+\/(.*?) (.*)/);
console.log(namespace,JSON.parse(jsonString));
Explanation
^\w+ // any alpha string from start
\/ // forward slash
(^.*?) // group from slash to whatever comes next in this case the space
// space
(.*) // group from after space to end
I am trying to replace a substring within a string with an exact number of other characters.
Example:
Input: Hello There, General Kenobie!
Output: xxxxx There, xxxxxxx Kenobie!
I can get this to work if I replace it with a preset string:
const text = "'Hello' There, 'General' Kenobie!"
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;
console.log(text.replace(pattern, "xxx"));
Output: xxx There, xxx Kenobie!
What am I missing wrapping my head around.
Thanks!
You are using a hard-coded string of 'xxx' as your replacement string. So, that's what you are seeing... the string(s) replaced with 'xxx'.
The .replace() method actually supports a function as the replacement, instead of a string, so that's what you need here.
Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
const text = "'Hello' There, 'General' Kenobie!"
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;
const newText = text.replace(pattern, (str, m) => 'x'.repeat(m.length));
console.log(newText);
You can always loop through the matches and replace each separately.
let text = "'Hello' There, 'General' Kenobie!"
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;
let array1;
while ((array1 = pattern.exec(text)) !== null) {
wrap = array1[0][0];
text = text.replace(array1[0],wrap + "x".repeat(array1[0].length-2) + wrap);
}
console.log(text)
I have a string like this:
const myString = "["dupa", "dupa", "dupa"]";
how to use regex in JS/TS to remove all characters " and [ and ]?
i need only dupa, dupa, dupa
thanks for any help
It will return you string with other removed from it and with your double quoted there is problem with it. So use single quote.
const myString = '["dupa", "dupa", "dupa"]';
const a = myString.replace(/[\[\]']+/g, '').replace(/"/g, '');
console.log(a);
You will get "dupa, dupa, dupa"
Or you can go with :
const myString = '["dupa", "dupa", "dupa"]';
const a = JSON.parse(myString);
console.log(a.join(", "))
I have the following string:
let str = '/user/:username/'
I want to extract replace username with harry with colon removed.
I tried the following:
const regex = /[^:]+(?=:)/g
str.replace(regex, x => console.log(x))
Try: /:\w+/
let str = '/user/:username/'
str.replace(/:\w+/, "harry")
// => "/user/harry/"
let str = '/user/:username/';
let html = str.replace(":username", "harry");
console.log(html);
var str = '/user/:username/';
var newstr = str.replace(/:username/i, "harry");
print(newstr);
hi pal, is this what you are looking for? i found it at https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/replace
you can use like that :
let str = '/user/:username/';
str.replace(':username','harry')
// o/p => /user/harry/"
In your regex [^:]+(?=:) you are matching 1+ times not a colon and assert that at the end there should be a colon resulting in a match for /user/
If you want to use the negated character class you could match a colon and then not a forward slash:
:[^\/]+
const str = `/user/:username/`;
const result = str.replace(/:[^\/]+/, "harry");
console.log(result);