I am working on a project where I work with the regex function.
Here is my code in jsFiddle
and the HTML is here
<div >
<a href='/'>color=(green) title=(Hello World) caption=(Hello City 2) post=(New)</a>
</div>
and js is here
$(".post-body").each(function() {
var e = $(this),
t = e.find("a").text();
if (t) {
var a = t.match(/title=\(([^)]*)\)\s caption=\(([^)]*)\)/);
if (a) {
var s = a[1];
0 != s && e.find("a").text(s), 0 != i && e.find("a").text(i)
}
}
});
This code works fine but when I put color and post values then the code stops working.
I don't know why are all values not showing like My World Hello City 2 New
?
Here below when I tried to put values then code doesn't work, I also want that there should be optional so that we can use either use one value or all values like just use of two values title and caption in this case, or we can use all values like color=(green) title=(Hello World) caption=(Hello City 2) post=(New)
$(".post-body").each(function() {
var e = $(this),
t = e.find("a").text();
if (t) {
var a = t.match(/title=\(([^)]*)\)\s caption=\(([^)]*)\)\s post=\(([^)]*)\)\s color=\(([^)]*)\)\s content=\(([^)]*)\)\s size=\(([^)]*)\)/);
if (a) {
var s = a[1],
i = a[2];
m = a[3];
n = a[4];
z = a[5];
y = a[6];
0 != s && e.find("a").text(s), 0 != i && e.find("a").text(i), 0 != m && e.find("a").text(m), 0 != n && e.find("a").text(n), 0 != z && e.find("a").text(z), 0 != y && e.find("a").text(y)
}
}
});
On research, I found a code created by someone that works fine maybe it's helpful to fix my problem
But this is code created by an expert developer and it's copyrighted the same like this I am trying to create my own genuine code but it's not working. I hope here I will get some solution. Any kind of help is highly appreciated!
CodePudding user response:
You can use this regex to match with all existing fields into your syntax like this /(?:([a-zA-Z]{3,}) =\(([^)]*)\))/g
and use matchAll to get all of them into an array and loop through the array like this if you want to show the results somewhere:
$(".post-body").each(function() {
var e = $(this),
t = e.find("a").text();
if (t) {
var a = [...t.matchAll(/(?:([a-zA-Z]{3,}) =\(([^)]*)\))/g)];
if (a) {
a.map(function(item, key){
console.log(item)
let k = item[1];
let v = item[2];
$("#results").append(`<span>${v}</span>`);
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<a href='/'>color=(green) title=(Hello World) caption=(Hello City 2) post=(New) title=(Hello World 3)</a>
</div>
<br />
<div id="results">
</div>