Convert text to link base on char receive - javascript

I have a post that contains a content body, the text in content body need to be properly formatted.
If the content contain a special keyword #, # i want to convert it to a usefull link.
content = "These is a sample post it can contain any thing and i can mention people with #username and show hastag reference #stackoverflowQuestion";
newContent = content.split(" ");
username = [];
hashtag = [];
newContent.forEach((sub) => {
at = sub.indexOf("#");
tag = sub.indexOf("#");
if(at == 0){
trendname.push(sub)
}
if(tag == 0){
hashtag.push(sub)
}
return sub;
});
username.forEach((user) => {
user.link = user.replace(/#/, "/${user}");console.log(user.link);
return user;}); console.log(user.link);
hashtag.forEach((str) => {
str.taged= str.replace(/([a-z])([A-Z])/g, '$1 $2').toLowercase;
return str;}); console.log(str.taged);
Firstly the code above is not loging vakue outside the loop.
Secondly is there any other way to re-write these sode because it look in efficient. if there is Please specify.
Thanks

your question is a little bit complicated to understand I think... But anyways I hope the following will help you somehow.
First, you can simplify your first loop to:
let usernames = content.match(/#([^ ]*)/g)
let hashtags = content.match(/#([^ ]*)/g)
Those are regex, and they work as follow:
They begin with # or # (if you are looking for usernames or hashtags)
[^ ]* means "Everything but a white space, and multiple times (*)
So now, you can construct user objects:
let users = usernames.map(username => {
return {
username: username,
link: '/' + username.slice(1, username.length)
}
}) // --> [ { username: '#username', link: '/username' } ]
Here is the complete code I wrote:
let content = "These is a sample post it can contain any thing and i can mention people with #username and show hastag reference #stackoverflowQuestion";
let usernames = content.match(/#([^ ]*)/g)
let hashtags = content.match(/#([^ ]*)/g)
let users = usernames.map(username => {
return {
username: username,
link: '/' + username.slice(1, username.length)
}
})
console.log(users)
Something is wrong with your code. You are making a forEach on an array of strings, and then you try to set a property to that string: user.link = ....
Secondly, you are trying to log values outside of your loops, and doing so puts you out of the scope of the loop. So you can't log those variables and this is completely normal because they just don't exist anymore... Try to indent your code better, you'll see it directly.
Hope this helps, and try working a little bit on the redaction of your questions, the stack overflow community can be harsh some times

Related

Javascipt replacing exact numbers in an array

am trying to replace numbers in an array but am facing an issue which am not really able to correctly manage regarding how to correctly target the just one data I really have to change.
I'll make an example to have more accuracy on describing it.
Imagine my data array look like that:
["data", "phone numbers", "address"]
I can change numbers via following script but my first problem is that it makes no differences between the number it find in columns, for example "phone numbers" from "address" (at the moment am not using it, but should I include a ZIP code in the address it would be really be a problem)
Beside, my second and current problem with my script, is that obviosuly in the same "phone numnbers" a number may appear more times while I'd like to affect only the first block of the data - let's say to add/remove the country code (or even replace it with it's country vexillum) which I normally have like that "+1 0000000000" or "+54 0000000000"
So if a number is for example located in EU it really make this script useless: Spain is using "+34" while France "+33" and it wouldn't succeded in any case becouse it recognize only "+3" for both.
I've found some one else already facing this problems which seems to solved it wrapping the values inside a buondaries - for example like that "\b"constant"\b" - but either am wronging syntax either it does not really apply to my case. Others suggest to use forEach or Array.prototype.every which I failed to understand how to apply at this case.
Should you have other ideas about that am open to try it!
function phoneUPDATES(val)
{
var i= 0;
var array3 = val.value.split("\n");
for ( i = 0; i < array3.length; ++i) {
array3[i] = "+" + array3[i];
}
var arrayLINES = array3.join("\n");
const zero = "0";
const replaceZERO = "0";
const one = "1";
const replaceONE = "1";
const result0 = arrayLINES.replaceAll(zero, replaceZERO);
const result1 = result0.replaceAll(one, replaceONE);
const result2 = result1.replaceAll(two, replaceTWO);
const result3 = result2.replaceAll(thre, replaceTHREE);
const result4 = result3.replaceAll(four, replaceFOUR);
const result5 = result4.replaceAll(five, replaceFIVE);
const result6 = result5.replaceAll(six, replaceSIX);
const result7 = result6.replaceAll(seven, replaceSEVEN);
const result8 = result7.replaceAll(eight, replaceEIGHT);
const result9 = result8.replaceAll(nine, replaceNINE);
const result10 = result9.replaceAll(ten, replaceTEN);
const result11 = result10.replaceAll(eleven, replaceELEVEN);
Why not use a regex replace, you could do something like /(\+\d+ )/g which will find a + followed by one or more digits followed by a space, and then you can strip out the match:
const phoneNumbers = [, "+54 9876543210"]
console.log(phoneNumbers.map((num) => num.replaceAll(/(\+\d+ )/g, '')))
If you need to only target the second element in an array, i'd imagine your data looks like
const data = [["data", "+1 1234567890, +1 5555555555", "address"], ["data", "+11 111111111, +23 23232323", "address"]];
console.log(data.map((el) => {
el[1] = el[1].replaceAll(/(\+\d+ )/g, '');
return el;
}))
ok, this almost is cheating but I really didn't thought it before and, by the way does, not even actually solve the problems but jsut seems to work around it.
If I call the replacemente in decreasing order that problem just does not show up becouse condition of replacement involving higher numbers are matched before the smaller one.
but should some one suggest a complete "true code comply" solution is wellcome

Translate Special Characters with npm latinize is not working dynamically

I am using latinize to translate german language's special characters to English, they module work only when I pass string within single or double quotes, but not when I pass by storing them inside a variable.
import latinize from 'latinize';
ANd inside render, I console this and it works fine,
console.log('render', latinize('VfL Osnabrück'))
also when i pass my
let tag_name = 'VfL Osnabrück';
console.log('render', latinize('VfL Osnabrück'))
it will again works fine, but did not work fine when I get tag_name from my api. And complete code is below
let tag_parsing = sub_category_id.split('%20');
let tag_string = '';
for (let i = 0; i < tag_parsing.length; i++) {
tag_parsing[i];
// tag_parsing[0] == Vlf
// tag_parsing[1] == Osnabrück
console.log('latinized text', tag_parsing[i]);
tag_string += ' ' + tag_parsing[i]
}
OUTPUT
output of latinized text ==> Osnabr%C3%BCck
output of latinized text inside quotes ==> Osnabruck
I also try with .toString() but did not work
I think there may be something off with how you are attempting to process the query string from the URL.
Here's a snippet of the logic I used to process your query string in a forked codesandbox. I used a functional component for ease, but the same logic can be used in a class-based component.
// get the search string
const { search } = useLocation();
const [latinizedValue, setLatinizedValue] = React.useState("");
React.useEffect(() => {
console.log({ search });
// create search params object
const newParams = new URLSearchParams(search);
const key = newParams.get("key");
const value = newParams.get("value")?.trim();
console.log("Param", key, `"${value}"`);
console.log("latinize param:", `"${latinize(value)}"`);
setLatinizedValue(latinize(value));
}, [search]);
Demo
The font-family that i was using was not contains special german characters, and finally I changed the font-family that supports german special characters, and everything goes smooth and latinize also works fine.

Unable to Get Output From While Loop in Javascript

I'm working on my final project of the Winter 2017 quarter to demonstrate how to use Regular Expressions in both C# and JavaScript code behind pages. I've got the C# version of my demonstration program done, but the JavaScript version is making me pull what little hair I have left on my head out (no small achievement since I got a fresh buzz cut this morning!). The problem involves not getting any output after applying a Regular Expression in a While loop to get each instance of the expression and printing it out.
On my HTML page I have an input textarea, seven radio buttons, an output textarea, and two buttons underneath (one button is to move the output text to the input area to perform multiple iterations of applying expressions, and the other button to clear all textareas for starting from scratch). Each radio button links to a function that applies a regular expression to the text in the input area. Five of my seven functions work; the sixth is the one I can't figure out, and the seventh is essentially the same but with a slightly different RegEx pattern, so if I fix the sixth function, the seventh function will be a snap.
(I tried to insert/upload a JPG of the front end, but the photo upload doesn't seem to be working. Hopefully you get the drift of what I've set up.)
Here are my problem children from my JS code behind:
// RegEx_Demo_JS.js - code behind for RegEx_Demo_JS
var inputString; // Global variable for the input from the input text box.
var pattern; // Global variable for the regular expression.
var result; // Global variable for the result of applying the regular expression to the user input.
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder()
{
var strings = [];
this.append = function (string)
{
string = verify(string);
if (string.length > 0) strings[strings.length] = string;
}
this.appendLine = function (string)
{
string = verify(string);
if (this.isEmpty())
{
if (string.length > 0) strings[strings.length] = string;
else return;
}
else strings[strings.length] = string.length > 0 ? "\r\n" + string : "\r\n";
}
this.clear = function () { strings = []; };
this.isEmpty = function () { return strings.length == 0; };
this.toString = function () { return strings.join(""); };
var verify = function (string)
{
if (!defined(string)) return "";
if (getType(string) != getType(new String())) return String(string);
return string;
}
var defined = function (el)
{
// Changed per Ryan O'Hara's comment:
return el != null && typeof(el) != "undefined";
}
var getType = function (instance)
{
if (!defined(instance.constructor)) throw Error("Unexpected object type");
var type = String(instance.constructor).match(/function\s+(\w+)/);
return defined(type) ? type[1] : "undefined";
}
}
Within the code of the second radio button (which will be the seventh and last function to complete), I tested the ScriptBuilder with data in a local variable, and it ran successfully and produced output into the output textarea. But I get no output from this next function that invokes a While loop:
function RegEx_Match_TheOnly_AllInstances()
{
inputString = document.getElementById("txtUserInput").value;
pattern = /(\s+the\s+)/ig; // Using an Flag (/i) to select either lowercase or uppercase version. Finds first occurrence either as a standalone word or inside a word.
//result = pattern.exec(inputString); // Finds the first index location
var arrResult; // Array for the results of the search.
var sb = getStringBuilder(); // Variable to hold iterations of the result and the text
while ((arrResult = pattern.exec(inputString)) !==null)
{
sb.appendLine = "Match: " + arrResult[0] ;
}
document.getElementById("txtRegExOutput").value = sb.toString();
/* Original code from C# version:
// string pattern = #"\s+(?i)the\s+"; // Same as above, but using Option construct for case insensitive search.
string pattern = #"(^|\s+)(?i)the(\W|\s+)";
MatchCollection matches = Regex.Matches(userTextInput, pattern);
StringBuilder outputString = new StringBuilder();
foreach (Match match in matches)
{
string outputRegExs = "Match: " + "\"" + match.Value + "\"" + " at index [" + match.Index + ","
+ (match.Index + match.Length) + "]" + "\n";
outputString.Append(outputRegExs);
}
txtRegExOutput.Text = outputString.ToString();
*/
} // End RegEx_Match_The_AllInstances
I left the commented code in to show what I had used in the C# code behind version to illustrate what I'm trying to accomplish.
The test input/string I used for this function is:
Don’t go there. If you want to be the Man, you have to beat The Man.
That should return two hits. Ideally, I want it to show the word that it found and the index where it found the word, but at this point I'd be happy to just get some output showing every instance it found, and then build on that with the index and possibly the lastIndex.
So, is my problem in my While loop, the way I'm applying the StringBuilder, or a combination of the two? I know the StringBuilder code works, at least when not being used in a loop and using some test data from the site I found that code. And the code for simply finding the first instance of "the" as a standalone or inside another word does work and returns output, but that doesn't use a loop.
I've looked through Stack Overflow and several other JavaScript websites for inspiration, but nothing I've tried so far has worked. I appreciate any help anyone can provide! (If you need me to post any other code, please advise and I'll be happy to oblige.)

Javascript Regular Expression to attempt to split name into Title/First Name(s)/Last Name

I want to try and detect the different parts of a person's name in Javascript, and cut them out so that I can pass them onto something else.
Names can appear in any format - for example:-
miss victoria m j laing
Miss Victoria C J Long
Bob Smith
Fred
Mr Davis
I want to try and write something simple, that'll do it's best to guess these and get them right 80% of the time or so (We have some extremely dodgy data)
I'm thinking of something along the lines of using a regex to check whether it has a prefix, then branch off to two places as to whether it has
/^(Dr|Mr|Mrs|Miss|Master|etc).? /
And then cutting the rest of it out using something like
/(\w+ )+(\w+)/
To match last name and other names. Though, I'm unsure on my greedy/ungreedy options here, and whether I can do soemthing to shortcut having all the different paths that might be available. Basically, hoping to find something simple, that does the job in a nice way.
It's also got to be written in Javascript, due to the limitations of the ETL tool I'm using.
Why not split() and just check the resulting parts:
// Split on each space character
var name = "Miss Victoria C J Long".split(" ");
// Check the first part for a title/prefix
if (/^(?:Dr|Mr|Mrs|Miss|Master|etc)\.?$/.test(name[0])) {
name.shift();
}
// Now you can access each part of the name as an array
console.log(name);
//-> Victoria,C,J,Long
Working Demo: http://jsfiddle.net/AndyE/p9ra4/
Of course, this won't work around those other issues people have mentioned in the comments, but you'd struggle on those issues even more with a single regex.
var title = '';
var first_name = '';
var last_name = '';
var has_title = false;
if (name != null)
{
var new_name = name.split(" ");
// Check the first part for a title/prefix
if (/^(?:Dr|Mr|Mrs|Miss|Master)\.?$/i.test(new_name[0]))
{
title = new_name.shift();
has_title = true;
}
if (new_name.length > 1)
{
last_name = new_name.pop();
first_name = new_name.join(" ");
}
else if(has_title)
{
last_name = new_name.pop();
}
else
{
first_name = new_name.pop();
}
}
Adapted from Accepted Answer :)

Javascript RegEx Help

I want to take strings like:
Submit Changes
Create New
Update Record
Save Item
and convert them to:
Submitting Changes
Creating New
Updating Record
Saving Item
with a function like:
var ConvertToProgressivePresent = (function(){
// cache this regex
var rProgressivePresent = /\b(?:(Submi(t))|(Creat|Sav|Updat)e)\b/i;
return function(phrase){
return phrase.replace(rProgressivePresent, "$1$2$3ing");
};
}());
This above regex works but doesn't seem like the best way to do it. I don't like the grouping here where 1-2 groups are always empty when there is a match.
Got any suggestions or improvements?
If you have specific words to replace with then you could make a word bank. Have the words and their replacement stored in an object and then loop through it.
var ConvertToProgressivePresent = (function() {
var replaceValues = {
"Submit": "Submitting",
"Create": "Creating",
"Update": "Updating",
"Save": "Saving"
}
return function(phrase) {
for (var item in replaceValues) {
phrase = phrase.replace(item, replaceValues[item]);
}
return phrase;
};
}());
Here is a JSFiddle Example
I think you should probablly use CASE statments instead. Regex isn't the most efficient way of doing things...and that is probably best that it doesn't cuz you know the old saying.
Wow, I have this problem...I know, I'll use regex...ok, now you have two problems 90)
First off, it doesn't appear to me that your regex does quite what you want anyway in that I don't see a second "t" added when changing submit to submitting.
However, I don't think I would use regex for this task at all anyway. If you are just trying to replace one word with another, and the word always comes at the beginning of the string, I might do something like:
function ReplaceIfBeginsWith(wholeString, checkFor, replaceWith)
{
if (wholeString.indexOf(checkFor + ' ') == 0)
{
return replaceWith + ' ' + wholeString.substr(checkFor.length + 1);
}
if (wholeString == checkFor)
{
return replaceWith;
}
return wholeString;
}
Then, you can call the function with each of the words you would want to replace. If you want case-insensitivity, just check against lowercase versions of all the strings.

Categories