Replacing an exact text from textarea - javascript

I have this little problem with jQuery. I want to remove an specific text from textarea. Check my codes:
Textarea values:
aa
a
aaa
i tried this:
$("#id_list").val($("#id_list").val().replace("a", " "));
The codes above only works if the text in each line is unique with no matching characters from other lines.
Now the problem is the codes above removes the first letter from aa, instead of removing the second line a. How can I get it to work in replace/removing an exact word on a line from textarea? Any help would be much appreciated.

Use word boundary.
Do this:
$("#id_list").val($("#id_list").val().replace(/\ba\b/g, " "));
That will replace only a
If you want to replace just one time, remove g from my regex.
If you want to use strings stored in a variable, do this:
var word = "a";
var regex = new RegExp("\\b"+word+"\\b","g");
$("#id_list").val($("#id_list").val().replace(regex, " "));

Just use replace(/a/g, " ")) instead. the /g flag means you search globally for the "a" letter. Without it you just replace the first occurrence.

You need to use regex replace
replace(/a/g, " "))

Related

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.

Regex with multiple start and end characters that must be the same

I would like to be able to search for strings inside a special tag in a string in JavaScript. Strings in JavaScript can start with either " or ' character.
Here an example to illustrate what I want to do. My custom tag is called <my-tag. My regex is /('|")*?<my-tag>((.|\n)[^"']*?)<\/my-tag>*?('|")/g. I use this regex pattern on the following strings:
var a = '<my-tag>Hello World</my-tag>'; //is found as expected
var b = "<my-tag>Hello World" + '</my-tag>'; //is NOT found, this is good!
var c = "<my-tag>Hello World</my-tag>"; //is found as expected
var d = '<my-tag>something "special"</my-tag>'; //here the " char causes a problem
var e = "<my-tag>something 'special'</my-tag>"; //here the " char causes a problem
It works well with a and also c where it finds the tag with the containing text. It also does not find the text in b which is what I want. But in case d and e the tag with content is not found due to the occurrence of the " and ' character. What I want is a regex where inside the tag " is allowed if the string is start with ', and vice versa.
Is it possible to achieve this with one regex, or is the only thing I can do is to work with two separate regex expressions like
/(")*?<my-tag>((.|\n)[^']*?)<\/my-tag>*?(")/g and /(')*?<my-tag>((.|\n)[^"]*?)<\/my-tag>*?(')/g ?
It's not pretty, but I think this would work:
/("<my-tag>((.|\n)[^"]*?)<\/my-tag>"|'<my-tag>((.|\n)[^']*?)<\/my-tag>')/g
You should be able to use de match from the first match ('|") and reuse it for the second match. Something like the following:
/('|")<my-tag>.*?<\/my-tag>\1/g
This should make sure to match the same character at the beginning and the end.
But you really shouldn't use regex for parsing HTML.

regex to match only quotes that aren't in links

can you tell me how I can in javascript using regex to select quoted text, but not the one that is in the link
so I don't want to select these quotes some text
I want to select only normal quoted text
I used
result = content.replace(/"(.*?)"/g, "<i>$1</i>");
to replace all quoted text with italic, but it replaces also href quotes
Thanks :)
If you need an adhoc regex solution, you may match and capture tags, and only replace " symbols in other contexts. Defining a tag as <+non-<s up to the first >, we may use
var s = '"replace this" but <div id="not-here"> "and here"</div>';
var re = /(<[^<]*?>)|"(.*?)"/g;
var result = s.replace(re, function (m,g1,g2) {
return g1? g1 : '<i>' + g2 + '</i>';
});
console.log(result);
The (<[^<]*?>)|"(.*?)" matches:
(<[^<]*?>) - Group 1 (g1 later in the callback) that captures <, 0+ symbols other than < as few as possible up to the first >
| - or
"(.*?)" - ", 0+ chars other than a newline as few as possible captured into Group 2 (g2 later) and a ".
In the callback method, Group 1 is checked for a match, and if yes, we just put the tag back into the result, else, replace with the tags.
The simplest answer would be to use:
/[^=]"(.*)"/
instead of
/"(.*?)"/
But that will also include quotes that have = sign before them.
Why not only work on the actual text of the element... Like:
var anchors = [],
idx;
anchors = Array.prototype.slice.call(document.getElementsByTagName("a"));
for(idx=0; idx<anchors.length; idx++) {
anchors[idx].innerHTML = anchors[idx].innerHTML.replace(/"([^"]*)"/g, '<i>$1</i>');
}
some text that contains a "quoted" part.
<br/>
more "text" that contains a "quoted" part.
Here we get all anchor elements as an array and replace the innerHTML text with a italicized version of itself.
This pattern could be what you're looking for: <.+>.*(\".+\").*</.+>
Used in JavaScript, the following matches "text":
new RegExp('<.+>.*(\".+\").*</.+>', 'g').exec('some "text"')[1]

Regular Expression word boundary breaks on '-'

I have a string in the following format.
"ad60 ad60-12 ad60 12-ad60"
now I want to find the matches only where "ad60" is written.
I started off with
/\bad60\b/i
but regex finds that '-' is not part of the character string. which returns 4 matches.
I tried many things but they all either return 4 matches or return nothing.
Any kind of help would be appreciated.
You can use:
var s = "ad60 ad60-12 ad60 12-ad60";
var r = s.replace(/(^|\s)ad60(?=\s|$)/g, "$1##");
//=> ## ad60-12 ## 12-ad60
this should find any word starting from letter
/[a-z][a-z\d]+/i
ADDED
if you wish to find any words which are included ad60 string try this
/[a-z\d\-\_]*ad60[a-z\d\-\_]*/i
but words separated by space will not get in result
"ad60 ad60-12 ad60 12-ad60".match(/(^ad60\s+)|(\s+ad60$)|(\s+ad60\s+)|(^ad60$)/ig);
will result in ["ad60 ", " ad60 "]
then you can trim the white spaces in matched elements.

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