Regular expression filter angular2 - javascript

I am working on an autocomplete functionality where regex has been used for filtering. The filter code currently is as below:
filterStates(val: string) {
return val ? this.states.filter(s => new RegExp(`^${val}`, 'gi').test(s.name))
: this.states;
}
}
Above regex worked fine for data structure like:
states=[{"name":"Alaska",code:1234},
{"name":"Bulgaria",code:12345},
{"name":"Colarado",code:12346},
{"name":"New Jersey",code:12347},
]
Heres the working plunker:https://plnkr.co/edit/Pf2pWeUYo2mt7VzwCDs2?p=preview
But now there is a slight change in the data structure as shown in the name below:
states=[{"name":"Alaska (AL)","code":1234},
{"name":"Bulgaria (BG)","code":12345},
{"name":"Colarado (CO)","code":12346},
{"name":"New Jersey (NJ)","code":12347},
]
I am not able to figure out as to how to generate the regex for name. I am a complete noob when it comes to regular expressions.
Any help would be much appreciated.

Use this regular expression to extract state name (no need to trim) : ^[\w ]+(?= \()
Alaska (AL) => match Alaska
Bulgaria (BG) => match Bulgaria
New Jersey (NJ) => match New Jersey
Here is a demo on regex101
Other possibility which will match states when you type
Replace
return val ? this.states.filter(s => new RegExp(`^[\w ]+(?= \()`, 'gi').test(s.name))
: this.states;
with
return val ? this.states.filter(s => (s && s.name && s.name.toLowerCase().substring(0, val.length) === val))
: this.states;
Here is a plunker, try to type a then l

Related

Array of unicode char to string : strange behavior

I try to reduce the size of my Fontawesome icon fonts.
First I parse my css file for retrieving all the unicode codes
with
const numericValue = parseInt(unicodeHex, 16)
const character = String.fromCharCode(numericValue)
glyphList.push(character)
Next I generate a string with
const glyphListStr = glyphlist.join(' ')
console.log(glyphListStr)
It gives       (tested it contains \uF5EC \uE00F \uF4CD \uE022 \uE2CE \uF3CA ) it is OK
My strange behavior.
Working code
const fontmin = new Fontmin()
.use(Fontmin.glyph({
text: '     ' ,//glyphListStr
hinting: false
}))
But when I use the variable it fails:
What I make wrong?
const fontmin = new Fontmin()
.use(Fontmin.glyph({
text: glyphListStr, //'     '
hinting: false
}))
After many hours I decided to upgrade my typescript to 4.8.2
and I cannot understand why but now it is working !
It was probably a wrong type somewhere.

React JS - How to escape brackets [h2] Title [/h2] using React Markdown v8.0.3 library?

I am doing a React News Component where I get some text from an API and I have to display it in my UI.
Sample of the text I have to escape:
[img]{STEAM_CLAN_IMAGE}/3703047/17e3e74c5f323f431ec172c81940e81ad52588b3.jpg[/img]\n\n[h2]The Arlington Major[/h2]\nThe Summer Tour of the DPC draws to a close.
Head over to the [url=www.dota2.com/battlereport]full update
website[/url] for all the details.
As you can see, the HTML tags are marked with brackets [ ] and I don't know how to escape them and to convert in html tags.
Code here:
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import React from 'react;
return (<div>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw]}
components={{ h2: 'p'}}>
{text}
</ReactMarkdown>
</div>)
The brackets are being literally ignored and the text is displayed as you can see below.
[img]{STEAM_CLAN_IMAGE}/3703047/17e3e74c5f323f431ec172c81940e81ad52588b3.jpg[/img]
[h2]The Arlington Major[/h2] The Summer Tour of the DPC draws to a
close, and The Arlington Major offers the best teams in the world a
final chance at DPC points before the competitive road reaches The
International. Catch all the action as it unfolds from August 4 - 14
in Arlington, Texas, USA.
Head over to the [url=www.dota2.com/battlereport]full update
website[/url] for all the details.
I've tried to use the replace function from JavaScript but this solution is not really practical and I would like to know if there are better and nicer solutions.
And if you know how to make all the text to be wrapped with only a div or some html element because the actual behaviour of React Markdown is to wrap it block by block with a p element.
That doesn't look like markdown - it looks like BBCode which is why you're running into problems. Markdown has a very specific syntax.
There seem to be a few converters available. For example this one, or perhaps this one (which has an online version that you can use for some preliminary testing).
You may have to do a little searching/research to find one that works best for you.
Okay mister Andy, I've fixed the problem thanks to you.
So I will let here the function for this type of markup (BBCode) for anyone that have the same problem as me. Take in consideration after you apply this function on your text you still have to use React Markdown to convert the text to HTML.
export function convertBBC(param) {
// preprocessing for tf2toolbox BBCode
if (param.search(/TF2Toolbox/gim) != -1) {
param = param
.replace(
/(\(List generated at .+?\[\/URL\]\))((?:.|\n)+)/gim,
'$2\n\n\n$1'
) //Move TF2Toolbox link to bottom
.replace('(List generated at', '(List generated from')
.replace(/[^\S\n]+\(List/gim, '(List')
.replace(/\[b\]\[u\](.+?)\[\/u\]\[\/b\]/gim, '[b]$1[/b]\n') //Fix double emphasized titles
.replace(/(\n)\[\*\]\[b\](.+?)\[\/b\]/gim, '$1[*] $2');
}
const STEAM_CLAN_IMAGE =
'https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/clans/';
//general BBcode conversion
param = param
.replace(/\[b\]((?:.|\n)+?)\[\/b\]/gim, '**$1**') //bold; replace [b] $1 [/b] with ** $1 **
.replace(/\[\i\]((?:.|\n)+?)\[\/\i\]/gim, '*$1*') //italics; replace [i] $1 [/u] with * $1 *
.replace(/\[\u\]((?:.|\n)+?)\[\/\u\]/gim, '$1') //remove underline;
.replace(/\[s\]((?:.|\n)+?)\[\/s\]/gim, '~~ $1~~') //strikethrough; replace [s] $1 [/s] with ~~ $1 ~~
.replace(/\[center\]((?:.|\n)+?)\[\/center\]/gim, '$1') //remove center;
.replace(/\[quote\=.+?\]((?:.|\n)+?)\[\/quote\]/gim, '$1') //remove [quote=] tags
.replace(/\[size\=.+?\]((?:.|\n)+?)\[\/size\]/gim, '## $1') //Size [size=] tags
.replace(/\[color\=.+?\]((?:.|\n)+?)\[\/color\]/gim, '$1') //remove [color] tags
.replace(
/\[list\=1\]((?:.|\n)+?)\[\/list\]/gim,
function (match, p1, offset, string) {
return p1.replace(/\[\*\]/gim, '1. ');
}
)
.replace(/{STEAM_CLAN_IMAGE}/gim, STEAM_CLAN_IMAGE)
.replace(/\[img\]((?:.|\n)+?)\[\/img\]/gim, '![$1]($1)')
.replace(/\[url=(.+?)\]((?:.|\n)+?)\[\/url\]/gim, '[$2]($1)')
.replace(/\[\h2\]((?:.|\n)+?)\[\/\h2\]/gim, '*$1*')
.replace(/\[\h1\]((?:.|\n)+?)\[\/\h1\]/gim, '<h1>$1</h1>')
.replace(/(\n)\[\*\]/gim, '$1* ') //lists; replcae lists with + unordered lists.
.replace(/\[\/*list\]/gim, '')
.replace(/\[img\]((?:.|\n)+?)\[\/img\]/gim, '![$1]($1)')
.replace(/\[url=(.+?)\]((?:.|\n)+?)\[\/url\]/gim, '[$2]($1)')
.replace(/\[code\](.*?)\[\/code\]/gim, '`$1`')
.replace(
/\[code\]((?:.|\n)+?)\[\/code\]/gim,
function (match, p1, offset, string) {
return p1.replace(/^/gim, ' ');
}
)
.replace(/\[php\](.*?)\[\/php\]/gim, '`$1`')
.replace(
/\[php\]((?:.|\n)+?)\[\/php\]/gim,
function (match, p1, offset, string) {
return p1.replace(/^/gim, ' ');
}
)
.replace(/\[pawn\](.*?)\[\/pawn\]/gim, '`$1`')
.replace(
/\[pawn\]((?:.|\n)+?)\[\/pawn\]/gim,
function (match, p1, offset, string) {
return p1.replace(/^/gim, ' ');
}
);
//post processing for tf2toolbox BBCode
if (param.search(/TF2Toolbox/gim) != -1) {
param = param
.replace(
'/bbcode_lookup.php))',
"/bbcode_lookup.php) and converted to /r/tf2trade ready Markdown by Dum's [converter](http://jondum.github.com/BBCode-To-Markdown-Converter/))."
) //add a linkback
.replace(/\*\*.+?\*\*[\s]+?None[\s]{2}/gim, ''); //remove empty sections
}
return param;
}
IMAGE FOR LISTS OUTCOME
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw]}
components={{ list: 'ol', h1: 'h4' }}
>
{convertBBC(body)}
</ReactMarkdown>
IMAGE FOR LINKS WITH IMAGES OUTCOME
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw]}
>
{convertBBC(location.state.body)}
</ReactMarkdown>
Thanks again guys!

String.split() method on object property set via API

Hi I'm having a hard time understanding why .split isn't working on the string I am passing.
This is my string parser that returns the string as separate <p> tags
const formatString = (str) => {
return str.split('\n').map((line, index) =>
<p key={index}>{line}</p>
)
}
I'm using an API that returns an object with a description property and a meta property.
Here's what the description value would display in the debugger:
description: "Level : Lv.3\nType : Creature\n\nA special monster that's only available on the ice
island of Rien. One of the grown Murus featuring an unusually thick lips."
When I pass that property into my formatString() function, it doesn't split the string and return the separate <p> enclosed strings, rather its the original input that gets returned. I also set the input as a variable and passed that instead and received my expected output.
expected output:
Level : Lv.3
Type : Creature
A special monster that's only available on the ice island of Rien. One of the grown Murus featuring an
unusually thick lips."
I've tried using a value declared both via useRef() and useState() and that seems to not matter. As far as immutability goes, .split() doesn't change the string, so I don't see why my function can't parse it.
Here is a link to the simulated problem on codesandbox:
https://codesandbox.io/s/amazing-maxwell-dhs4k?file=/src/App.js
Escape \ by using \\
const formatString = (str) => {
return str.split('\\n').map((line, index) =>
<p key={index}>{line}</p>
)
}
Replace all concurrences with a wildcard like {{n}}, and then do the split.
const formatString = (str) => {
return str.replace(/\\n/gi,'{{n}}')
.split('{{n}}')
.map((line, index) => <p key={index}>{line}</p>);
};

Find a string in structured HTML and replace it while maintaining the structure

Let's say I have the following text:
...at anyone who did not dress...
, where I need to find and replace "did not" with "did't" The task is simple until the text has styles and it becomes:
...at anyone who <span style='color: #ff0000;'>did</span>not dress...
If I just do
obj.innerText.replace("did not", "did't"),
then the style will not be saved, and
obj.innerHtml.replace("did not", "did't")
will not find
Is there an elegant solution?
UDP: there is a position in the text of the beginning and end of a phrase/word, as well as an index in case of repetition
const html = document.getElementsByTagName('p')[0].innerHTML;
const tags = html.match(/<\/?[^>]+(>|$)/g) || [];
const textTrue = html
.replace(/<\/?[^>]+(>|$)/g, '')
.replace('did not', "didn't");
var lastIndex = 0;
const tagsIndexs = tags.map((item) => {
lastIndex = html.indexOf(item, lastIndex);
return lastIndex;
});
const output = tags ? tags.reduce((result, tag, index) => {
return (
result.substr(0, tagsIndexs[index]) +
tag+
result.substr(tagsIndexs[index])
);
}, textTrue): textTrue;
document.getElementById('result').innerHTML = output;
<p>d<span style="color: #FF0000">id </span>not</p>
<div id='result'></div>
if 'not' is not styled(as shown in the example) the best approach I can think of is find all 'did' occurrences and then check if there is 'not' in the neighborhood. If yes remove the 'not' and replace the did with didn't. It is however performance intensive since you can not go for replace, but use indexOf in a while loop and manipulate the html string manually. Additionally if the styling varies(<span>,<b>,<i>..) it will be very difficult(if not impossible) to come with a valid criteria to evaluate the existence of 'not' in the neighborhood of the 'did'. The same approach can be used on 'not' instead of did, but again it really depends on the styling you need to preserve.

Regular Expression: pull part from string. with JS

Hey all im not every good with regexp i was hoping someone could help.
ok so this is the sting "KEY FOUND! [ 57:09:91:40:32:11:00:77:16:80:34:40:91 ]"
And i need to pull "57:09:91:40:32:11:00:77:16:80:34:40:91", now this key can be meany length not just as written here and with or with out the ":"
now the second sting i would like to test and extract is: "[00:00:09] Tested 853 keys (got 179387 IVs)", i would like to pull "00:00:09" and "853" and "179387".
this would be the raw string http://regexr.com?31pcu or http://pastebin.com/eRbnwqn7
this is what im doing now.
var pass = new RegExp('KEY FOUND\!')
var tested = new RegExp('Tested')
var fail = new RegExp('\Failed. Next try with ([0-9]+) IVs')
var data="Look at the link i added"
if (tested.test(data)) {
self.emit('update', mac, {
'keys' : data.split('Tested ')[1].split(' keys ')[0],
'ivs' : data.split('got ')[1].split(' IVs')[0]
});
} else if (pass.test(data)) {
var key = data.split('KEY FOUND! [')[1].split(' ]')[0].split(':').join('');
} else if (fail.test(data)) {
console.log(data);
}
thanks all
Edit:
I have added more the the question to help with the answer
If it is always surrounded by [] then it is simple:
\[([\s\S]*)\]
This will match any characters enclosed by [].
See it in action here.

Categories

Resources