Replace whole words only using Regex - javascript

I am trying to replace some letters in a textarea with some text from an input box.
The problem that I am facing is that it replaces all the values that are specified in CN.
For example, if CN is "A", then "A" will be replaced as well as "A" in "Apple". I want to replace only "A". I have tried using chordName = CN + " ", but that replaces values only where CN is in the middle of a sentence, not at the beginning of a line.
This is my code:
function doit(CN, SC) {
var rawLyrics = document.getElementById("ttbox").value;
var chordName = CN;
var spnCode = SC;
var res = rawLyrics.replace(new RegExp(chordName, 'g'), spnCode);
results.innerText = res;
}
I also have the problem where "results" textarea gets refreshed with the replaced words rather than changing only the required words i.e, I am using the above code to replace different words in a single block of text, so once I replace one word, and move on to the next, the previously replaced word comes back to it's previous state.
What am I doing wrong? Any solutions?

Related

JavaScript: Replace certain occurrence of string depending on selection index

I've created my own autocomplete feature and I've come across a bug I'd like to fix. Here's an example of an incomplete sentence I might want to autocomplete the final word for:
let text = 'Hello there, I am her'
In my functionality the user clicks ctrl + enter and it autcompletes the word with a suggestion displayed on the page. In this case let's say the suggestion is 'here'. Also my controller knows where the user is based on the insertion cursor (so I have the index).
If I use replace like so:
text.replace(word, suggestion);
(Where word is 'her' and suggestion is 'here') it will replace the first occurrence. Obviously there are endless combinations of where this word might be in the text, how do I replace one at a certain index in text string? I know I can do it through some messy if conditions, but is there an elegant way to do this?
(If it is relevant I am using angular keydown/keyup for this)
EDIT>>>>>
This is not a duplicate on the question linked as in that case they are always replacing the last occurrence. If I did that then my program wouldn't support a user going back in their sentence and attempting to autocomplete a new word there
So, you have a position in a string and a number of characters to replace (=length of an incomplete word). In this case, would this work?
let text = 'appl and appl and appl'
function replaceAt(str, pos, len, replace) {
return str.slice(0, pos) + replace + str.slice(pos + len);
}
console.log(replaceAt(text, 0, 4, 'apple'))
console.log(replaceAt(text, 9, 4, 'apple'))
Gonna point you in a direction that should get you started.
let sentence = 'Hello lets replace all words like hello with Hi';
let fragments = sentence.split(' ');
for (let i=0; i<fragments.length; i++){
if(fragments[i].toLowerCase() == 'hello')
fragments[i] = 'Hi'
}
let formattedsentence = fragments.join(' ');
console.log(formattedsentence); //"Hi lets replace all words like Hi with Hi"

Regext to match any substring longer than 2 characters

regex-pattern-to-match-any-substring-matching exact characters longer-than-two-characters-from-a-provided input,where ever exact string matches
Only pot or potato should be highlighted, instead of ota or ot, when user type pota and click search button.
Please find code below where matched string is highlighted.
// Core function
function buildRegexFor(find) {
var regexStr = find.substr(0,3);
for (var i = 1; i < find.length - 2; i++) {
regexStr = '(' + regexStr + find.substr(i+2,1) + '?|' + find.substr(i,3) + ')';
}
return regexStr;
}
// Handle button click event
document.querySelector('button').onclick = function () {
// (1) read input
var find = document.querySelector('input').value;
var str = document.querySelector('textarea').value;
// (2) build regular expression using above function
var regexStr = buildRegexFor(find);
// (3) apply regular expression to text and highlight all found instances
str = str.replace(new RegExp(regexStr, 'g'), "<strong class='boldtxt'>$1</strong>");
// (4) output
document.querySelector('span').textContent = regexStr;
document.querySelector('div').innerHTML = str;
};
consider "meter & parameter" as one string, if type meter in input box and click search button. meter should be highlighted as well as meter in parameter should highlight.Thanks in advance
Your for loop is set to go from i = 1, while i is less than find.length-2. find.length is 4. 4-2 is 2. So your for loop is set to go from i = 1 while i is less than 2. In other words, it's operating exactly once. I have no idea what you thought that for loop was going to do, but I'm betting that isn't it.
Prior to the for loop, regextr is set equal to the string pot (the first three characters of the find string. The first (and only) time through the for loop, it is set to a new value: the left paren, the existing value (pot), the fourth character of find (a), the question mark, the vertical bar, and three characters from find starting with the second. Put those together, and your regextr comes out to:
(pota?|ota)
That RegEx says to find either the string "pota" (with the a being optional, so "pot" also works) or the string "ota". So any instances of pota, pot, or ota will be found and highlighted.
If you just wanted "pota?", just eliminate the right half of that line inside the for loop. Better yet, replace the entire subroutine with just a line that appends the ? character to the find string.

Get first letter of last word of each span

I'm trying to get the first letter of the last word in every span on the page. I will then add this as a class (used for filtering).
Here is what I have so far:
$('.each-artist span').each(function() {
var artistName = $(this).text().toLowerCase(); // get text, convert to lowercase
var firstLetterSplice = artistName.slice(0, 1); // get first letter
$(this).parent().parent('.each-artist').addClass(firstLetterSplice); // add as class
});
So, this works fairly successfully, it takes the text of each .each-artist span, lowercases it, splices it to find first letter then adds this first letter as a class.
The only issue is I need to get the last word of each .each-artist span, not the first, then get the first letter of this last word and apply it as a class.
I have a jsFiddle set up for testing:
http://jsfiddle.net/rZbwQ/
You're almost there, just split by word boundary and then get the last word
$('.each-artist span').each(function () {
var artistName = $(this).text().toLowerCase().split(/\b/);
var firstLetterSplice = artistName.pop().slice(0, 1);
$(this).closest('.each-artist').addClass(firstLetterSplice);
});
FIDDLE

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"), ""));

JavaScript string replace() not working when replacing variable

I'm trying to create a JavaScript script for highlighting certain text on a page. Right now I'm having issues trying to replace text (from the body html) with other text. I want to replace all instances of each item in the array highlights with some other text.
The code that I'm using is:
var responseText = server.responseText;
var highlights = responseText.split("\n");
var text = document.body.innerHTML;
for (i in highlights) {
if (highlights[i].length > 1) {
var exp = new RegExp(highlights[i], "g");
console.log(exp);
console.log(highlights[i]);
text = text.replace(exp, "XXXXXXXXXXX");
}
}
document.body.innerHTML = text;
Currently, I am getting the correct value printouts for highlights[i] and I think I am for the regular expression exp; if highlights[i] is 'Remember', then the printout I'm getting for exp is '/Remember/g' (without the quotation marks) -- but it's not replacing the word 'Remember' on the page. 'And if I replace highlights[i] in the new RegExp() with simply the string "Remember" it works correctly. Any ideas on what's wrong?
EDIT:
I solved the problem! When creating the RegExp() I passed in highlights[i].trim() instead of just highlights[i] to get rid of whitespace at the beginning/end and it appears to be working now.
There is some problem with your multiline server.responseText .
I replaced the input with spaces instead of newlines, and all the replacements work fine :
http://jsfiddle.net/XTdgJ/1/

Categories

Resources