Replace last matched character in substring using jquery / regex - javascript

I know this question is similar to THIS so apologies if considered a duplicate.
The result I'm trying to achieve is to check divs with a class of gallery-info
$('.gallery-info').each(function() {
});
I set up a condition to return a substring if the character count of each div is greater than 140 characters. (Twitter)
$('.gallery-info').each(function() {
var descLength = 140;
var str = $(this).text();
var patt = new RegExp(/[,;.:!()&\s$]/g);
if (str.length > descLength) {
$(this).text(str.substr(0, descLength) + "...");
}
});
IF
The last character of the substring matches the patt var.
Return substring -1 and concat "..."
ELSE
Return substring and concat "..."
I've been having a brain fart on this and I believe I can achieve this in Vanilla JS with str.replace() and str.charAt() but I need to do this in jQuery.

I think updating your IF condition with below should work fine.
if (str.length > descLength) {
if(patt.test(str[descLength-1])) {
$(this).text(str.substr(0, descLength-1) + "...");
} else {
$(this).text(str.substr(0, descLength) + "...");
}
}
CODEPEN: https://codepen.io/azimjs/pen/mBqjNY

I think this works as you've described.
$('.gallery-info').each(function() {
var descLength = 140;
var str = $(this).text();
var patt = new RegExp(/[,;.:!()&\s$]/g);
if (str.length > descLength) {
var substring = str.substr(0, descLength);
var lastChar = substring[substring.length-1];
if (lastChar.match(patt)) {
$(this).text(str.substr(0, descLength -1) + "...");
} else {
$(this).text(str.substr(0, descLength) + "...");
}
}
});
Codepen
https://codepen.io/foozie3moons/pen/GMOBvw

Related

Javascript Hangman - Replace Character In String

I've seen similar questions asked on Stack Overflow regarding this topic, but I haven't seen anything specific that would help me. My issue is that I can't seem to figure out how to replace a dash in hiddenWord with a correctly guessed letter while still retaining the dashes for un-guessed letters. Here is what I have so far and I'm not even sure if it's on the right track.
<script type="text/javascript">
// Declaration of Variables
var wordPool= ["Alf", "MarriedWithChildren", "Cheers", "MASH", "CharlesInCharge", "FmailyTies", "KnightRider", "MagnumPI", "MiamiVice"];
var lives = 6;
var myLetter;
var letter;
var wordChoice;
var hiddenWord;
var i;
var enter;
// Selects word randomly from wordPool[]. Then replaces the letters with "- ".
function selectedWord() {
var number = Math.round(Math.random() * (wordPool.length - 1));
wordChoice = wordPool[number];
for(i = 0; i < wordChoice.length; i++){
hiddenWord = wordChoice.replace(/./g,"- ");
}
console.log(hiddenWord);
}
// Gives myLetter a value of key pressed. If key is "Enter" selectedWord() initiates
document.onkeyup = function(event) {
var myLetter = event.key;
if(myLetter === "Enter"){
selectedWord();
}
console.log(myLetter);
}
</script>
I have seen some stuff with jQuery and PHP but I have to do it in javascript for class. Any help would be appreciated and if this has been addressed before please let me know.
You can check each character at the word string, compare it with the chosen character and replace it, if it is the same character.
I changed your code a bit to reflect what you are looking for.
Also make sure to lowercase all characters to make it easier for the player.
// Declaration of Variables
var wordPool= ["Alf", "MarriedWithChildren", "Cheers", "MASH", "CharlesInCharge", "FmailyTies", "KnightRider", "MagnumPI", "MiamiVice"];
var lives = 6;
var myLetter;
var letter;
var wordChoice;
var hiddenWord;
var i;
var enter;
// Change character to selected one
function checkCharacter(n) {
for(i = 0; i < wordChoice.length; i++){
console.log(wordChoice[i].toLowerCase() + "==" + n);
if(wordChoice[i].toLowerCase() == n.toLowerCase()){
hiddenWord = setCharAt(hiddenWord,i,n);
}
}
console.log("[" + hiddenWord + "]");
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
// Selects word randomly from wordPool[]. Then replaces the letters with "- ".
function selectedWord() {
var number = Math.round(Math.random() * (wordPool.length - 1));
wordChoice = wordPool[number];
hiddenWord = wordChoice.replace(/./gi,"-");
console.log(wordChoice + "[" + hiddenWord + "]");
}
// Gives myLetter a value of key pressed. If key is "Enter" selectedWord() initiates
document.onkeyup = function(event) {
var myLetter = event.key;
if(myLetter === "Enter"){
if(lives == 0){
selectedWord();
lives = 6;
}else{
lives--;
}
}
console.log(myLetter);
checkCharacter(myLetter);
}
//Select a random word at start
selectedWord();
I made a JSfiddle that is working and playable:
Check it out here...
Try
hiddenWord += "- "
Instead of replace
Or
hiddenWord += wordChoice[i].replace(/./g,"- ");
Here's an example:
var word = "do this";
var displayWord = [];
for (var i = 0; i < word.length; i++) {//build array
if (word[i] === " ") {
displayWord.push(" ");
} else {
displayWord.push("-");
}
}
function update(userGuess) {//update array
for (var i = 0; i < word.length; i++) {
if (word[i] === userGuess) {
displayWord[i] = userGuess;
} else {
displayWord[i] = displayWord[i];
}
}
}
//Guess letters
update("h");
update("o");
displayWord = displayWord.join('');//convert to string
alert(displayWord);
Check out the pen - https://codepen.io/SkiZer0/pen/VbQKPx?editors=0110

replace odd and even occurence with html javascript

I am trying to replace ` ticks with html code in a string.
var str = "this `code` and `here`"
my expected output
"this code and here"
What i am trying to do is below
.
get the positions with ticks in a string
replace those ticks with span html based on odd and even occurence.
not sure, i couldnt get expected and my browser gets hang. and
when i debug it. i see there is no index for string to replace.
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
var pos = [];
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
pos.push(i);
}
}
if (pos.length > 1) {
for (var j = pos.length; j > 0; j--) {
var index = pos[j];
var spanHtml = '';
if (j % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
str = str.replaceAt(index, spanHtml);
}
}
You can use String.prototype.replace() with RegExp
/(`\w+`)/g
String.prototype.slice() with parameters 1, -1 to slice string within backtick
`
characters
var str = "this `code` and `here`";
var res = str.replace(/(`\w+`)/g, function(match) {
return "<span class='code'>" + match.slice(1, -1) + "</span>"
});
document.body.insertAdjacentHTML("beforeend", res);
.code {
background: turquoise;
}
scope of var i is wider then you think, so pos.push(i) will have them all same at the end
replaceAt appends incorrect ending
replaceAt shifts rest of the string invalidating positions you found
I believe you wanted something along these lines:
var str = "this `code` and `here`"
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+1);
}
var pos = [];
var count = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
var index = i;
var spanHtml = '';
if (count % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
count++;
str = str.replaceAt(index, spanHtml);
i+= spanHtml.length -1; // correct position to account for the replacement
}
}
console.log(str)
Use the JavaScript replace method.
var str = "this `code` and `here`";
var newStr = str.replace("`", "");

jQuery get numbers inside paragraph, but not those in classes

I have the following HTML structure:
<div class="content">
<p>somecontent</p>
<p>another content <span id="name-1">content</span> 1234214</p>
</div>
I want to wrap only numbers in additional span (1234214). So far I've made this:
jQuery(window).load(function() {
jQuery('.content p').html(function(index, value) {
return value.replace(/(\d+)/g, '<span class="mathjaxfont">$1</span>');
});
});
However this replaces the 1 in span id. How can I exclude checking element attributes?
You might want not only to exclude attributes (think about the h1-element for example) but constrain your replacing on the text nodes. See this questions for some ideas on how to get only and work with text nodes: How do I select text nodes with jQuery?
This answer in above question How do I select text nodes with jQuery? gives you a collection of text-nodes on which you can do your string-replacing.
You should use .contents() and .replaceWith() for this:
jQuery('.content p').contents().each(function() {
var method = this.nodeType == 1 ? 'html' : 'replaceWith';
$(this)[method](this.textContent.replace(
/(\d+)/g,
'<span class="mathjaxfont">$1</span>'
));
});
Here's a JSFiddle.
Long and hard solution, but should work in nested elements.
The idea is to handle element's .html() string character by character, wrapping numbers when they are found, but omitting numbers inside tags' definition.
Fiddle.
$(document).ready(function()
{
$('.content p').each(function()
{
$(this).html(handleHtml($(this).html()));
});
});
function handleHtml(html)
{
var resultHtml = "";
var numberStr = "";
var re = /[0-9]/;
var isTag = false, quote = "";
for (var i = 0; i < html.length; i++)
{
var char = html.substr(i, 1);
if (!isTag && re.test(char))
{
numberStr += char;
}
else
{
if (numberStr)
{
resultHtml += wrapNumber(numberStr);
numberStr = "";
}
resultHtml += char;
if (isTag && !quote && (char == '"' || char == "'"))
{
quote = char;
}
else if (quote && quote == char)
{
quote = "";
}
if (char == '<')
{
isTag = true;
}
else if (!quote && char == '>')
{
isTag = false;
}
}
}
if (numberStr)
{
resultHtml += wrapNumber(numberStr);
}
return resultHtml;
}
function wrapNumber(number)
{
return '<span class="mathjaxfont">' + number+ "</span>";
}

Remove extra white spaces from Array

The elements in my list should be
A1,A2,A3,A4
If user input A1,A2,A3,A4,,,,,,
or
A1,A2,,,A3,A4,,A5,,
or
A,B, ,, ,, V,,,, , , , , ,ddfd ,,,,,,,,
It should consider as
A1,A2,A3,A4
The logic written by me was
if(valueText !== null) { alert("Value Text..." + valueText);
valueList = valueText.split(",");
for (var i = 0; i < valueList.length; i++)
{
if (valueList[i] == "")
{
valueList.splice(i, 1);
alert("ValueList inside for if.."+valueList);
}
}
alert("ValueList.." + valueList);
}
But its not working properly
You can do something like this with match & join functions:-
var str = "A1,A2,,,A3,A4,,A5,,";
strnew = str.match(/[^ ,]+/g).join(',');
//Output--> A1,A2,A3,A4,A5
Hope this will help you...
You can do this with regex, for example:
var txt = 'A1,A2,,,A3,A4,,A5,,'
var res = txt.replace(/(,)\1*/g, ',').replace(/,$/, '');
//^ A1,A2,A3,A4,A5

how can i avoid counting double spaces as words?

$(document).ready(function() {
$("[class^='count[']").each(function() {
var elClass = $(this).attr('class');
var minWords = 0;
var maxWords = 0;
var countControl = elClass.substring((elClass.indexOf('['))+1, elClass.lastIndexOf(']')).split(',');
if(countControl.length > 1) {
minWords = countControl[0];
maxWords = countControl[1];
}
else { maxWords = countControl[0]; }
$(this).after('<div class="wordCount"><strong>0</strong> words so far</div>');
if(minWords > 0) {
$(this).siblings('.wordCount').addClass('error');
}
$(this).bind('keyup click blur focus change paste', function() {
var numWords = jQuery.trim($(this).val()).split(' ').length;
if($(this).val() === '') {
numWords = 0;
}
$(this).siblings('.wordCount').children('strong').text(numWords);
if(numWords < minWords || (numWords > maxWords && maxWords != 0)) {
$(this).siblings('.wordCount').addClass('error');
}
else {
$(this).siblings('.wordCount').removeClass('error');
}
});
});
});
this script basically counts the spaces between words but if extra spaces are added it counts them as new words too...
http://blog.themeforest.net/tutorials/creating-a-jquery-word-counter/
.split() also accepts regular expressions. Try this:
var numWords = jQuery.trim($(this).val()).split(/\s+/).length;
Remove all double spaces with a Regex and then do your script. If there are no double spaces to find, it cannot count them.
This is an example in C#, but the same accounts for javascript: How do I replace multiple spaces with a single space in C#?

Categories