javascript remove last occurrence on a given string - javascript

How to convert the following using js regex replace or something:
var text = "line1<br>line2<br>line3<br>line4<br>"
...js regex...
so that text becomes:
text = "line1<br>line2<br>line3<br>";
of course the number of br varies, and each line length varies too

Removing just the last line without regular expressions:
var text = "line1<br>line2<br>line3<br>line4<br>";
var pieces = text.split('<br>');
var newText = pieces.splice(0, pieces.length-2).join('<br>') + '<br>';
Note that this code makes at least three important assumptions:
The separator is always <br> and not, say, <br /> or <BR>.
The input string always ends with a <br>.
The result string always ends with <br>, even if it's otherwise empty! (For example, if the input string is line1<br> then the output will be <br>.

Here is one that I am posing just because I took the time to make it. It works but needs index and null checks and such.
var text = "line1<br>line2<br>line3<br>line4<br>";
var newText = text.substring(0, text.substring(0, text.length - 4).lastIndexOf("<br>"));

Related

Replce repeating set of character from end of string using regex

I want to remove all <br> from the end of this string. Currently I am doing this (in javascript) -
const value = "this is an event. <br><br><br><br>"
let description = String(value);
while (description.endsWith('<br>')) {
description = description.replace(/<br>$/, '');
}
But I want to do it without using while loop, by only using some regex with replace. Is there a way?
To identify the end of the string in RegEx, you can use the special $ symbol to denote that.
To identify repeated characters or blocks of text containing certain characters, you can use + symbol.
In your case, the final regex is: (<br>)*$
This will remove 0 or more occurrence of <br> from the end of the line.
Example:
const value = "this is an event. <br><br><br><br>"
let description = String(value);
description.replace(/(<br>)*$/g, '');
You may try:
var value = "this is an event. <br><br><br><br>";
var output = value.replace(/(<.*?>)\1*$/, "");
console.log(output);
Here is the regex logic being used:
(<.*?>) match AND capture any HTML tag
\1* then match that same tag zero or more additional times
$ all tags occurring at the end of the string

JS conditional RegEx that removes different parts of a string between two delimiters

I have a string of text with HTML line breaks. Some of the <br> immediately follow a number between two delimiters «...» and some do not.
Here's the string:
var str = ("«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>");
I’m looking for a conditional regex that’ll remove the number and delimiters (ex. «1») as well as the line break itself without removing all of the line breaks in the string.
So for instance, at the beginning of my example string, when the script encounters »<br> it’ll remove everything between and including the first « to the left, to »<br> (ex. «1»<br>). However it would not remove «2»some text<br>.
I’ve had some help removing the entire number/delimiters (ex. «1») using the following:
var regex = new RegExp(UsedKeys.join('|'), 'g');
var nextStr = str.replace(/«[^»]*»/g, " ");
I sure hope that makes sense.
Just to be super clear, when the string is rendered in a browser, I’d like to go from this…
«1»
«2»some text
«3»
«4»more text
«5»
«6»even more text
To this…
«2»some text
«4»more text
«6»even more text
Many thanks!
Maybe I'm missing a subtlety here, if so I apologize. But it seems that you can just replace with the regex: /«\d+»<br>/g. This will replace all occurrences of a number between « & » followed by <br>
var str = "«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>"
var newStr = str.replace(/«\d+»<br>/g, '')
console.log(newStr)
To match letters and digits you can use \w instead of \d
var str = "«a»<br>«b»some text<br>«hel»<br>«4»more text<br>«5»<br>«6»even more text<br>"
var newStr = str.replace(/«\w+?»<br>/g, '')
console.log(newStr)
This snippet assumes that the input within the brackets will always be a number but I think it solves the problem you're trying to solve.
const str = "«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>";
console.log(str.replace(/(«(\d+)»<br>)/g, ""));
/(«(\d+)»<br>)/g
«(\d+)» Will match any brackets containing 1 or more digits in a row
If you would prefer to match alphanumeric you could use «(\w+)» or for any characters including symbols you could use «([^»]+)»
<br> Will match a line break
//g Matches globally so that it can find every instance of the substring
Basically we are only removing the bracketed numbers if they are immediately followed by a line break.

ASCII character not being recognized in if statement

I am trying to get a string from a html page with jquery and this is what I have.
var text = $(this).text();
var key = text.substring(0,1);
if(key == ' ' || key == ' ')
key = text.substring(1,2);
text is this  Home
And I want to skip the space and or the keycode above It appears this code does not work either. It only gets the text.substring(0,1); instead of text.substring(1,2); because the if statement is not catching.= and I am not sure why. Any help would be super awesome! Thanks!
There are several problems with the code in the question. First,   has no special meaning in JavaScript: it is a string literal with six characters. Second, text.substring(1,2) returns simply the second character of text, not all characters from the second one onwards.
Assuming that you wish to remove one leading SPACE or NO-BREAK SPACE (which is what   means in HTML; it is not an Ascii character, by the way), then the following code would work:
var first = text.substring(0, 1);
if(first === ' ' || first === '\u00A0') {
text = text.substring(1, text.length);
}
The notation \u00A0 is a JavaScript escape notation for NO-BREAK SPACE U+00A0.
Should you wish to remove multiple spaces at the start, and perhaps at the end too, some modifications are needed. In that case, using a replace operation with regular expression is probably best.
If you want remove spaces at the beginning (and end) of a string, you can use the trim function
var myvar = " home"
myVar.trim() // --> "home"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

How to replace particular string from a multiline textarea using jQuery?

When i have string which consists of a single line, replace works just fine.
As soon as i type in some text into text area and press enter as for new line, replace won't work anymore.
var currentValue = $('#service-field').val();
$('#service-field').val(currentValue.replace("particular string",""));
What should I do?
Try this to make sure you capture all occurrences, and not just the ones on the first line:
$('#service-field').val(currentValue.replace(/particular string/g, ""));
Or with a variable:
var t = "particular string";
$('#service-field').val(currentValue.replace(eval("/" + t + "/g"), ""));

How do I read a list from a textarea with Javascript?

I am trying to read in a list of words separated by spaces from a textbox with Javascript. This will eventually be in a website.
Thank you.
This should pretty much do it:
<textarea id="foo">some text here</textarea>
<script>
var element = document.getElementById('foo');
var wordlist = element.value.split(' ');
// wordlist now contains 3 values: 'some', 'text' and 'here'
</script>
A more accurate way to do this is to use regular expressions to strip extra spaces first, and than use #Aron's method, otherwise, if you have something like "a b c d e" you will get an array with a lot of empty string elements, which I'm sure you don't want
Therefore, you should use:
<textarea id="foo">
this is some very bad
formatted text a
</textarea>
<script>
var str = document.getElementById('foo').value;
str = str.replace(/\s+/g, ' ').replace(/^\s+|\s$/g);
var words = str.split(' ');
// words will have exactly 7 items (the 7 words in the textarea)
</script>
The first .replace() function replaces all consecutive spaces with 1 space and the second one trims the whitespace from the start and the end of the string, making it ideal for word parsing :)
Instead of splitting by whitespaces, you can also try matching sequences of non-whitespace characters.
var words = document.getElementById('foo').value.match(/\S+/g);
Problems with the splitting method is that when there are leading or trailing whitespaces, you will get an empty element for them. For example, " hello world " would give you ["", "hello", "world", ""].
You may strip the whitespaces before and after the text, but there is another problem: When the string is empty. For example, splitting "" will give you [""].
Instead of finding what we don't want and split it, I think it is better to look for what we want.

Categories

Resources