How to wrap in span last three words from string / heading - javascript

I am trying to wrap last three words from string that will be a heading on site. I am trying with split method and with pop but not getting it.
var text = "This is an example text sentence"
i would like to look in html like this
This is an an example text sentence
var split = text.split(" ");
var last = split.pop() // but it gives me only the last word
text.join(" ") + (text.length > 0 ?
' <span class="text-stroke">' + last + "</span>" : last)

Use a regular expression to match \s+\S+ (spaces, followed by non-spaces) as many times as you want to match a word, followed by $ (the end of the string):
var text = "This is an example text sentence"
const newHTML = text.replace(
/(?:\s+\S+){3}$/,
'<span>$&</span>'
);
console.log(newHTML);

// split your text by spaces
let text = "This is an example text sentence.".split(/\s+/)
// rejoin your text
let nexText = text.slice(0, text.length-3).join(' ')
+ ' <span>'
+ text.slice(text.length-3).join(' ')
+ '</span>'
console.log(nexText)
// => This is an <span>example text sentence.</span>

Related

Javascript RegExp Allow Spaces Inside Pattern

I need to replace all "*text*" into "<strong>text</strong>"
when passing text = "normal text *words to be bolded* continue normal text" it doesn't work because of the spaces, it works only for single-word text.
wanted result: "normal text <strong>words to be bolded</strong> continue normal text"
result: "normal text *words to be bolded* continue normal text"
I need this function to work for whatever the text is:
function bold(text){
reg = /\*(\w+)\*/g
return text.replaceAll(reg, "<strong>" + text.split(reg)[1] + "</strong>")
}
You should allow a set of characters to be there. Right now, you have the sequence of characters fixed.
function bold(text){
reg = /\*([\w\s]+)\*/g
return text.replaceAll(reg, "<strong>" + text.split(reg)[1] + "</strong>")
}
You can use the array split method.
const str = "word1 word2 pla pla";
const newStr = [];
str.split(" ").forEach((val) => {
newStr.push(`<strong>${val}</strong> `);
});
console.log(newStr);
I assume that by 'words to be bolded', you are trying to match anything that is not asterisk.
function bold(text){
let reg = /\*([^\*]*)\*/g;
return text.replaceAll(reg, "<strong>$1</strong>")
};
let result = bold("normal1 *bold1 including space!* normal2 *bold2, including space?* normal3");
console.log(result);

How to replace specific letters in string without touching the words and letters inside quotes

I am trying to replace all spaces in a string expect if the spaces are inside quotes. I want the text inside the quotes to not to be touched at all.
I know this regexr !((".+")|('.+')) but I don't know how to implement it.
const value = " text text ' text in quotes no touch' "
value.replaceAll(' ', '+')
// wanted results "+text+text+' text in quotes no touch'+"
my goal
value.replaceAll(if !((".+")|('.+')) then change ' ' to '+")
You can use an expression string OR space and a callback function that returns + only if the match is a space:
const value = " text text ' text in quotes no touch' "
const repl = value.replace(/'.+?'| /g, m => m === ' ' ? '+' : m)
console.log(repl)
To handle escaped quotes, the "string" part can be refined to '(\\.|[^'])+'
const value = " text text ' text in \\' quotes no touch' "
const repl = value.replace(/'(\\.|[^'])+'| /g, m => m === ' ' ? '+' : m)
console.log(repl)
Alternative to regular expressions (which perhaps supply a better solution), you could traverse the string and infer, that every odd encounter of a quote marks the beginning of a quoted sentence:
value.split("'").map((line, index) => {
if (index % 2 == 0)
// Even encounters of a quote --> We are outside a quote, so we replace
return line.replaceAll(' ','+')
else
// Odd encounters --> We are inside a quote, so do nothing
return line
}).join('\'')
As an alternative you could first split the string and then apply the replacement only to the substrings that don't start with a quote:
const value = " text text ' text in quotes no touch' "
const splits = value.split(/('.+')/g) // [" text text ", "' text in quotes no touch'", " "]
const replaced = splits.map(substr =>
substr.startsWith("'") ? substr : substr.replaceAll(" ", "+")
).join("")
console.log(replaced)

RegEx Data Values Javascript white Space

I am trying to add the correct white space for data i am receiving. currently it shows like this
NotStarted
ReadyforPPPDReview
this is the code i am using
.replace(/([A-Z])/g, '$1')
"NotStarted" shows correct "Not Started" but "ReadyforPPPDReview" shows "Readyfor P P P D Review" when it should look like this "Ready for PPPD Review"
what is the best way to handle both of these using one regex or function?
You would need an NLP engine to handle this properly. Here are two approaches with simple regex, both have limitations:
1. Use list of stop words
We blindly add spaces before and after the stop words:
var str = 'NotStarted, ReadyforPPPDReview';
var wordList = 'and, for, in, on, not, review, the'; // stop words
var wordListRe = new RegExp('(' + wordList.replace(/, */g, '|') + ')', 'gi');
var result1 = str
.replace(wordListRe, ' $1 ') // add space before and after stop words
.replace(/([a-z])([A-Z])/g, '$1 $2') // add space between lower case and upper case chars
.replace(/ +/g, ' ') // remove excessive spaces
.trim(); // remove spaces at start and end
console.log('str: ' + str);
console.log('result1: ' + result1);
As you can imagine the stop words approach has some severe limitations. For example, words formula input would result in for mula in put.
1. Use a mapping table
The mapping table lists words that need to be spaced out (no drugs involved), as in this code snippet:
var str = 'NotStarted, ReadyforPPPDReview';
var spaceWordMap = {
NotStarted: 'Not Started',
Readyfor: 'Ready for',
PPPDReview: 'PPPD Review'
// add more as needed
};
var spaceWordMapRe = new RegExp('(' + Object.keys(spaceWordMap).join('|') + ')', 'gi');
var result2 = str
.replace(spaceWordMapRe, function(m, p1) { // m: matched snippet, p1: first group
return spaceWordMap[p1] // replace key in spaceWordMap with its value
})
.replace(/([a-z])([A-Z])/g, '$1 $2') // add space between lower case and upper case chars
.replace(/ +/g, ' ') // remove excessive spaces
.trim(); // remove spaces at start and end
console.log('str: ' + str);
console.log('result2: ' + result2);
This approach is suitable if you have a deterministic list of words as input.

jQuery Replace Second Space of Sentence

I want to replace second space occurrence of the sentence with a br.
I have tried this but it is deleting the rest.
var title = "My Title Needs Brace".split(" ").slice(0, 2).join(" ");
That will do the trick:
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Let's break it and see how it works:
First, we take the string and split it. we'll use " " as our separator
"My Title Needs Brace".split(' ')
// ["My", "Title", "Needs", "Brace"]
Second, we'll use reduce to combine the array back into one string
["My", "Title", "Needs", "Brace"]
.reduce(function (str, part) { return str + ' ' + part }, '');
// "My Title Needs Brace"
Why reduce and not join?
The advantage of reduce over join is that it allows us to use a function, which will give us a fine-grained control over how we join back each part of the string
Now, all that left is to replace the 2nd space with <br/>,
for that, we'll use the 3rd argument of the reduce function, which stands for the index, and ask:
is this the 3rd part? use <br/>
otherwise, use " "
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Note that this is the index of the string "part", not the spaces between them so the index is 2, not 1.
More about:
split
reduce
join
Try the following:
var title = "My Title Needs Brace".split(" ");
title.forEach(function(item, i, title){
if(i==1)
title[i] += "<br/>";
else
title[i] += ' ';
})
console.log(title.join(''));
I want to replace second space occurrence of the sentence with a br.
The simple way to do that is to add "<br/>" to the second element.
Here is the Code.
$(document).ready(function(){
var title = "My Title Needs Brace".split(" ");
title[1] = title[1]+"<br/>";
var newstr = title.join(" ");
$("#textd").html(newstr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textd">
</div>
maybe that will help :
var title = "My Title Needs Brace".split(" ");
t1=title [0]; My
t2=title[1]; // Title
t3=title[2]; // Needs
t4=title[3]; // Brace
you can drew here anything :
var htmlString = '' + t1 +''+ t2 + '<br />' + t3 +''+ t4 + '';
$('Anywhere').append(htmlString);
You can do this without splitting the string:
var title = 'My Title Needs Brace'.replace(/( .*?) /, '$1<br>');
Here, String.replace takes a RegExp and a string as arguments. The regex matches everything from the first space up through the second space, keeping everything except the second space in a capturing group. The string replaces the entire match with the contents of the capturing group, followed by '<br>'. Since the capturing group doesn't include the second space, this effectively only replaces the second space.

Display only whole word using javascript

I have a text say "A sample text for testing". I need to display only ten characters in a div.
so i do substring on the text
txt.substring(0,10)
This gives me "A sample t". Since its ugly to display a unterminated word, i need only to display "A Sample" to be displayed. How do i do this?
You could do what you do, substringing the text to 10 chars.
Then you use txt.lastIndexOf(' ') to find the last space in the text.
Then you use that to substring the text again.
Example:
var txt = "A Sample Text";
txt = txt.subString(0,10); // "A Sample T"
txt = txt.subString(0, txt.lastIndexOf(' ')); // "A Sample"
Let me know if it helps!
Assuming that you'd rather have a cut off string than an empty string, if the word is longer than ten characters:
function shorten(txt)
{
// if it's short or a space appears after the first 10 characters, keep the substring (simple case)
if (txt.length <= 10 || txt[10] === ' ') return txt;
// get the index of the last space
var i = txt.substring(0, 11).lastIndexOf(' ');
// if a space is found, return the whole words at the start of the string;
// otherwise return just the first 10 characters
return txt.substring(0, i === -1 ? 11 : i);
}
use substring method to do this
i think you should add a filter to check whether the 11th character is space or not with the substring method. otherwise the last valid word too might removed. get "New sample text for testing" for example.
this is the code.
str = "A sample text for testing"
ch11_space = (str[10] == ' ') ? 0 : 1;
str = str.substring(0,10);
if (ch11_space) {
str = str.substring(0,str.lastIndexOf(' '));
}
function getShortenedString(str)
{
var maxLength = 10; // whatever the max string can be
var strLength = str.length;
var shortenedStr = str.substr(0, maxLength);
var shortenedStrLength = shortenedStr.length;
var lastSpace = str.lastIndexOf(" ");
if(shortenedStrLength != strLength)
{
// only need to do manipulation if we have a shortened name
var strDiff = strLength - shortenedStrLength;
var lastSpaceDiff = shortenedStrLength - lastSpace;
if(strDiff > lastSpaceDiff) // non-whole word after space
{
shortenedStr = str.substr(0, lastSpace);
}
}
return shortenedStr;
}

Categories

Resources