The problem: I want to get all of the square brackets' content, and then delete them, but only if the brackets are at the beginnig of the string.
For example, a given string [foo][asd][dsa] text text text will return array with all of the three brackets' content (["foo", "asd", "dsa"]), and the string will become text text text.
But if the string looks like that: [foo] text [asd][dsa] text text, it'll take only the [foo], and the string will become: text [asd][dsa] text text.
How can I do that using JavaScript?
The loop checks the start of the string for anything in square brackets, takes the contents of the brackets, and removes the whole lot from the start.
var haystack = "[foo][asd][dsa] text text text";
var needle = /^\[([^\]]+)\](.*)/;
var result = new Array();
while ( needle.test(haystack) ) { /* while it starts with something in [] */
result.push(needle.exec(haystack)[1]); /* get the contents of [] */
haystack = haystack.replace(needle, "$2"); /* remove [] from the start */
}
Something like var newstring = oldstring.replace(/\[\w{3}]/, "");
You could proceed using a while, taking the first, adding it to an array, remove it and then do all again. This would give this :
var t1 = "[foo][asd][dsa] text text text";
var rule = /^(?:\[([^\]]*)\])/g;
var arr = new Array();
while(m = rule.exec(t1)){
arr.push(m[1]);
t1 = t1.replace(rule, "")
}
alert(arr); // foo,asd,dsa
alert(t1); // text text text
Related
I am not familiar with Javascript Regex. Can anyone tell me how to convert strings like "Minus162Plus140" into "-162,140", or "Plus162Minus140" into "162,-140" by using match or replace? thanks so much in advance!
Building on the previous answer, you'll also need to handle other cases, like "Plus162Minus140":
text = "Minus162Plus140";
text = text.replace(/^Minus/, "-"); // Handle when Minus comes first
text = text.replace("Minus", ",-"); // And second
text = text.replace(/^Plus/, ""); // Handle when Plus comes first
text = text.replace(/Plus/, ","); // And second
But this approach itself is brittle, and assumes that the string will always be of the form /^(Minus|Plus)\d+(Minus|Plus)\d+$/, which you could validate first with a regular expression:
if (/^(Minus|Plus)\d+(Minus|Plus)\d+$/) {
... do the replacement
} else {
... handle the error
}
You can just use string replace:
text = "Minus162Plus140";
text = text.replace("Minus", ",-");
text = text.replace("Plus", ",+");
console.log(text);
Or regex:
text = "Minus162Plus140";
re = /Plus/;
text = text.replace(re, ',+');
re = /Minus/;
text = text.replace(re, ',-');
// Then to remove the initial comma:
re = /^,/;
text = text.replace(re, '');
console.log(text);
This question already has answers here:
Parsing BBCode in Javascript
(2 answers)
Closed 3 years ago.
I've tags in string like [note]some text[/note] where I want to extract the inside text between the tags.
Sample Text:
Want to extract data [note]This is the text I want to extract[/note]
but this is not only tag [note]Another text I want to [text:sample]
extract[/note]. Can you do it?
From the given text, extract following:
This is the text I want to extract
Another text I want to [text:sample] extract
We can try matching using the following regex pattern:
\[note\]([\s\S]*?)\[\/note\]
This says to just capture whatever comes in between [note] and the closest closing [/note] tag. Note that we use [\s\S]* to potentially match desired content across newlines, should that be necessary.
var re = /\[note\]([\s\S]*?)\[\/note\]/g;
var s = 'Want to extract data [note]This is the text I want to extract[/note]\nbut this is not only tag [note]Another text I want to [text:sample]\n extract[/note]. Can you do it?';
var m;
do {
m = re.exec(s);
if (m) {
console.log(m[1]);
}
} while (m);
I wrote this while Tim posted his answer and it's quite like but I figured I'll post it anyway since it's extracted to a re-usable function you can use for any tag.
const str = `Want to extract data [note]This is the text I want to extract[/note]
but this is not only tag [note]Another text I want to [text:sample]
extract[/note]. Can you do it?`;
function extractTagContent(tag, str) {
const re = new RegExp(`\\[${tag}\\](.*?)\\[\\/${tag}\\]`, "igs");
const matches = [];
let found;
while ((found = re.exec(str)) !== null) {
matches.push(found[1]);
}
return matches;
}
const content = extractTagContent("note", str);
// content now has:
// ['This is the text I want to extract', 'Another text I want to [text:sample] extract. Can you do it?']
Demo: https://codesandbox.io/s/kw006560oo
I have a string that has the following format: <strong>FirstName LastName</strong>
How can I change this into an array with the first element firstName and second lastName?
I did this, but no luck, it won't produce the right result:
var data = [myString.split('<strong>')[1], myString.split('<strong>')[2]]
How can I produce ["firstName", "lastName"] for any string with that format?
In order to parse HTML, use the best HTML parser out there, the DOM itself!
// create a random element, it doesn't have to be 'strong' (e.g., it could be 'div')
var parser = document.createElement('strong');
// set the innerHTML to your string
parser.innerHTML = "<strong>FirstName LastName</strong>";
// get the text inside the element ("FirstName LastName")
var fullName = parser.textContent;
// split it into an array, separated by the space in between FirstName and LastName
var data = fullName.split(" ");
// voila!
console.log(data);
EDIT
As #RobG pointed out, you could also explicitly use a DOM parser rather than that of an element:
var parser = new DOMParser();
var doc = parser.parseFromString("<strong>FirstName LastName</strong>", "text/html");
console.log(doc.body.textContent.split(" "));
However, both methods work perfectly fine; it all comes down to preference.
Just match everything between <strong> and </strong>.
var matches = "<strong>FirstName LastName</strong>".match(/<strong>(.*)<\/strong>/);
console.log(matches[1].split(' '));
The preferred approach would be to use DOM methods; create an element and get the .textContent then match one or more word characters or split space character.
let str = '<strong>FirstName LastName</strong>';
let [,first, last] = str.split(/<[/\w\s-]+>|\s/g);
console.log(first, last);
/<[/\w\s-]+>|\s/g
Splits < followed by one or more word, space or dash characters characters followed by > character or space to match space between words in the string.
Comma operator , within destructuring assignment is used to omit that index from the result of .split() ["", "FirstName", "LastName", ""].
this is my approach of doing your problem. Hope it helps!
var str = "<strong>FirstName LastName</strong>";
var result = str.slice(0, -9).substr(8).split(" ");
Edit: it will only work for this specific example.
Another way to do this in case you had something other than an html
var string = "<strong>FirstName LastName</strong>";
string = string.slice(0, -9); // remove last 9 chars
string = string.substr(8); // remove first 8 chars
string = string.split(" "); // split into an array at space
console.log(string);
Let's say I have a string like so:
const sentence = "This is my custom string";
I want to highlight the words of a input field inside this sentence.
Let's say a say user typed a string and I have converted the separate words into an array like so:
["custom", "string", "is"]
I know want to replace the words in my sentence with a highlighted version of the words in my array. For a single word I would do something like this:
const word = 'custom';
const searchFor = new RegExp(`(${word})`, 'gi');
const replaceWith = '<strong class="highlight">$1</strong>';
const highlightedSentence = sentence.replace(searchFor, replaceWith);
How can I apply this logic with an array to the entire sentence?
I can't simply loop through it because the string will contain my highlighted class which will also be taken into the highlighting process the the second loop, third loop, etc.
This means that on a second loop if a user where to type:
"high custom"
I would highlight my highlighted class, leading to highlight inception.
For an example of what I mean try commenting/uncommenting the 2 highlighter functions:
https://jsfiddle.net/qh9ttvp2/1/
Your problem is that while replacing words, you replace already added html tag with .class 'highlight'.
Solution here could be to replace anything that is not html tag. Replace this line in you jsfiddle example.
const searchFor = new RegExp(`(${word})(?!([^<]+)?>)`, 'gi');
You can split you sentence into array and check if your element is already highlighted:
let sentence = "This is a some type of long string with all kinds of words in it, all kinds.";
let sentenceArr = sentence.split(' '); // make an array
const query = "kinds words all type";
function highlighter(query, sentence) {
const words = query.match(/\S+/g);
words.forEach((word) => {
// Create a capture group since we are searching case insensitive.
const searchFor = new RegExp(`(${word})`, 'gi');
const replaceWith = '<strong class="highlight">$1</strong>';
sentenceArr = sentenceArr.map(sw => (sw.indexOf('strong class="highlight"') === -1) ? sw.replace(searchFor, replaceWith) : sw); // if already highlited - skip
//sentence = sentence.replace(searchFor, replaceWith);
});
// console.log(sentence);
document.querySelector('.highlighted-sentence').innerHTML = sentenceArr.join(' '); // notice sentenceArr
}
// Works.
//highlighter('kinds words all type', sentence);
// Doesn't work.
highlighter('kinds words high', sentence);
<div class="highlighted-sentence"></div>
How do I get a long text string (like a querystring) to display a maximum of 10 characters, using JQuery?
Sorry guys I'm a novice at JavaScript & JQuery :S
Any help would be greatly appreciated.
If I understand correctly you want to limit a string to 10 characters?
var str = 'Some very long string';
if(str.length > 10) str = str.substring(0,10);
Something like that?
Creating own answer, as nobody has considered that the split might not happened (shorter text). In that case we don't want to add '...' as suffix.
Ternary operator will sort that out:
var text = "blahalhahkanhklanlkanhlanlanhak";
var count = 35;
var result = text.slice(0, count) + (text.length > count ? "..." : "");
Can be closed to function:
function fn(text, count){
return text.slice(0, count) + (text.length > count ? "..." : "");
}
console.log(fn("aognaglkanglnagln", 10));
And expand to helpers class so You can even choose if You want the dots or not:
function fn(text, count, insertDots){
return text.slice(0, count) + (((text.length > count) && insertDots) ? "..." : "");
}
console.log(fn("aognaglkanglnagln", 10, true));
console.log(fn("aognaglkanglnagln", 10, false));
var example = "I am too long string";
var result;
// Slice is JS function
result = example.slice(0, 10)+'...'; //if you need dots after the string you can add
Result variable contains "I am too l..."
And here's a jQuery example:
HTML text field:
<input type="text" id="myTextfield" />
jQuery code to limit its size:
var elem = $("#myTextfield");
if(elem) elem.val(elem.val().substr(0,10));
As an example, you could use the jQuery code above to restrict the user from entering more than 10 characters while he's typing; the following code snippet does exactly this:
$(document).ready(function() {
var elem = $("#myTextfield");
if (elem) {
elem.keydown(function() {
if (elem.val().length > 10)
elem.val(elem.val().substr(0, 10));
});
}
});
Update:
The above code snippet was only used to show an example usage.
The following code snippet will handle you issue with the DIV element:
$(document).ready(function() {
var elem = $(".tasks-overflow");
if(elem){
if (elem.text().length > 10)
elem.text(elem.text().substr(0,10))
}
});
Please note that I'm using text instead of val in this case, since the val method doesn't seem to work with the DIV element.
('very long string'.slice(0,10))+'...'
// "very long ..."
html
<p id='longText'>Some very very very very very very very very very very very long string</p>
javascript (on doc ready)
var longText = $('#longText');
longText.text(longText.text().substr(0, 10));
If you have multiple words in the text, and want each to be limited to at most 10 chars, you could do:
var longText = $('#longText');
var text = longText.text();
var regex = /\w{11}\w*/, match;
while(match = regex.exec(text)) {
text = text.replace(match[0], match[0].substr(0, 10));
}
longText.text(text);
What you should also do when you truncate the string to ten characters is add the actual html ellipses entity: …, rather than three periods.
Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:
.no-overflow {
white-space: no-wrap;
text-overflow: ellipsis;
overflow: hidden;
}
and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.
A = "a lennnnnnnnnnnnngthy string ";
word = A.substring(0, number_of_words_to_appear) + "...";
console.log(word)
This looks more to me like what you probably want.
$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow").text());
function getReplacementString(str){
return str.replace(/(https?\:\/\/[^\s]*)/gi,function(match){
return match.substring(0,10) + "..."
});
}});
you give it your html element in the first line and then it takes the whole text, replaces urls with 10 character long versions and returns it to you.
This seems a little strange to only have 3 of the url characters so I would recommend this if possible.
$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow p").text());
function getReplacementString(str){
return str.replace(/https?\:\/\/([^\s]*)/gi,function(match){
return match.substring(0,10) + "..."
});
}});
which would rip out the http:// or https:// and print up to 10 charaters of www.example.com
Try this :)
var mystring = "How do I get a long text string";
mystring = mystring.substring(0,10);
alert(mystring);
#jolly.exe
Nice example Jolly. I updated your version which limits the character length as opposed to the number of words. I also added setting the title to the real original innerHTML , so users can hover and see what is truncated.
HTML
<div id="stuff">a reallly really really long titleasdfasdfasdfasdfasdfasdfasdfadsf</div>
JS
function cutString(id){
var text = document.getElementById(id).innerHTML;
var charsToCutTo = 30;
if(text.length>charsToCutTo){
var strShort = "";
for(i = 0; i < charsToCutTo; i++){
strShort += text[i];
}
document.getElementById(id).title = "text";
document.getElementById(id).innerHTML = strShort + "...";
}
};
cutString('stuff');
const text = 'imathelongtextblablabla'
const showLess = false
{!showLess && `${text.substring(0, 10)}`}
{!showLess && "..."}
Show this "long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text "
to
long text long text long ...
function cutString(text){
var wordsToCut = 5;
var wordsArray = text.split(" ");
if(wordsArray.length>wordsToCut){
var strShort = "";
for(i = 0; i < wordsToCut; i++){
strShort += wordsArray[i] + " ";
}
return strShort+"...";
}else{
return text;
}
};