查找任何语言的#标签,并替换为字符串中的链接

问题描述 投票:0回答:2

从节点js中的字符串中找到#hashtag,例如:

我的字符串是:string = "I Love #भारत #ভারত #ભારત #ਭਾਰਤ #ଭାରତ #இந்தியா #ഇന്ത്യ #ಭಾರತ #భారత #india and the whole country."

输出:hashtag = ["भारत", "ভারত", "ભારત", "ਭਾਰਤ", "ଭାରତ", "இந்தியா", "ഇന്ത്യ", "ಭಾರತ", "భారత", "india"]

我还需要替换节点js中的字符串,例如

输入String = "I Love #भारत #ভারত #ભારત #ਭਾਰਤ #ଭାରତ #இந்தியா #ഇന്ത്യ #ಭಾರತ #భారత #india and the whole country.";

输出String = "I Love <a href='http://hostname/hashtag/भारत' target='_blank'>#भारत</a> <a href='http://hostname/hashtag/ভারত' target='_blank'>#ভারত</a> <a href='http://hostname/hashtag/ભારત' target='_blank'>#ભારત</a> <a href='http://hostname/hashtag/ਭਾਰਤ' target='_blank'>#ਭਾਰਤ</a> <a href='http://hostname/hashtag/ଭାରତ' target='_blank'>#ଭାରତ</a> <a href='http://hostname/hashtag/இந்தியா' target='_blank'>#இந்தியா</a> <a href='http://hostname/hashtag/ഇന്ത്യ' target='_blank'>#ഇന്ത്യ</a> <a href='http://hostname/hashtag/ಭಾರತ' target='_blank'>#ಭಾರತ</a> <a href='http://hostname/hashtag/భారత' target='_blank'>#భారత</a> <a href='http://hostname/hashtag/india' target='_blank'>#india</a> and the whole country.";

node.js mongodb hashtag unicode-string find-replace
2个回答
1
投票

这是你的字符串:

const str= "I Love #भारत #ভারত #ભારત #ਭਾਰਤ #ଭାରତ #இந்தியா #ഇന്ത്യ #ಭಾರತ #భారత #india and the whole country.";

从字符串匹配主题标签。

你可以使用match字符串方法。 Here是参考。

str.match(/(#\S*)/g);

您的代码变为:

const str = "I Love #भारत #ভারত #ભારત #ਭਾਰਤ #ଭାରତ #இந்தியா #ഇന്ത്യ #ಭಾರತ #భారత #india and the whole country.";

const result = str.match(/(#\S*)/g).map(hash=>hash.substr(1));

console.log(result);

用链接替换主题标签。

对于标签替换,您可以使用与字符串的replace方法相同的正则表达式。

这是你的代码:

const str = "I Love #भारत #ভারত #ભારત #ਭਾਰਤ #ଭାରତ #இந்தியா #ഇന്ത്യ #ಭಾರತ #భారత #india and the whole country.";


const result = str.replace(/(#\S*)/g, (hashtag) => {
  const hash=hashtag.substr(1);
  return `<a href='http://hostname/hashtag/${hash}' target='_blank'>${hash}</a>`
});

console.log(result);

0
投票
var main = "I Love #भारत #ভারত #ભારત #ਭਾਰਤ #ଭାରତ #இந்தியா #ഇന്ത്യ #ಭಾರತ #భారత #india and the whole country."

var myString = main.match(/(#\S*)/g);

console.log(myString);

示例:https://repl.it/repls/ChartreuseElectronicTransformation

© www.soinside.com 2019 - 2024. All rights reserved.