Using .replace() at a specific index - javascript

Is there a function that can replace a string within a string once at a specific index? Example:
var string1="my text is my text";
var string2="my";
string1.replaceAt(string2,"your",10);
and the resultant output would be "my text is your text", Or:
var string1="my text is my text";
var string2="my";
string1.replaceAt(string2,"your",0);
in which case the result would be "your text is my text".

function ReplaceAt(input, search, replace, start, end) {
return input.slice(0, start)
+ input.slice(start, end).replace(search, replace)
+ input.slice(end);
}
jsfiddle here
PS. modify the code to add empty checks, boundary checks etc.

From the "related questions" bar, this old answer seems to be applicable to your case. Replacing a single character (in my referenced question) is not very different from replacing a string.
How do I replace a character at a particular index in JavaScript?

Related

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]

How do I get a list of strings ending in a newline or ending in the end of the string in javascript regex?

I'm pretty frustrated with regex right now. Given:
var text = "This is a sentence.\nThis is another sentence\n\nThis is the last sentence!"
I want regex to return to me:
{"This is a sentence.\n", "This is another sentence\n\n", "This is the last sentence!"}
I think i should use
var matches = text.match(/.+[\n+\Z]/)
but \Z doesn't seem to work. Does javascript have an end of string matcher?
You can use the following regex.
var matches = text.match(/.+\n*/g);
Working Demo
Or you could match a newline sequence "one or more" times or the end of the string.
var matches = text.match(/.+(?:\n+|$)/g);
Try this one: /(.+\n*)/g
See it here: http://regex101.com/r/wK8oX3/1
If you wanted an array and didn't want to keep the "\n" around you could do...
var strings = text.split("\n");
which would yield
["This is a sentence.", "This is another sentence", "", "This is the last sentence!"]
if you wanted to get rid of that empty string chain a filter onto the split...
var strings = text.split("\n").filter(function(s){ return s !== ""; });
Maybe not what you want tho, also not as efficient as the regex options already proposed.
Edit: as torazaburo pointed out using Boolean as the filter function is cleaner than a callback.
var strings = text.split("\n").filter(Boolean);
Edit Again: I keep getting one upped, using the /\n+/ expression is even cooler.
var strings = text.split(/\n+/);
To get an array of sentences:
var matches = text.match(/.+?(?:(?:\\n)+|$)/g);
You can try this,
text.match(/.+/g)

regex not matching in findText()

I was trying to change color to some text in a document, and I required regexp.
So, I tried the function findText to search where my text is in the selected text, but I am having some troubles matching the regexps.
Look at this sample script
function onOpen() {
DocumentApp.getUi().createMenu('Test')
.addItem('Find regex in sel', 'findRegex'))
.addToUi();
}
function findRegex() {
var ui = DocumentApp.getUi();
var selection = DocumentApp.getActiveDocument().getSelection();
var txt = selection.getSelectedElements()[0].getElement().asText();
var inp = ui.prompt('Regex to search:').getResponseText();
var regex = new RegExp(inp);
ui.alert('Found in "' + txt.getText()
+ '"\n Re: ' + txt.findText(regex)
+ '\n In: ' + txt.findText(inp));
}
This prompts for something to search, then builds a regex out of it. Then both the regex and the original string are used to search in the selected text.
Well, I do not know what to do to get the regex matching: I am always getting null: if the text to be searched is "foobarbaz", and I input foo, only the plain string matches.
If instead I input /foo/, clearly nothing matches.
How should I use regexps to search using findText?
Consider that I have to "compose" regex, like /foobar/ + /\d+/, where foobar is the user-entered pattern.
Ok, I think to have found the crux: the regexp passed to findText is always a String object, even if it have a regexp inside.
I tried searching "fo+" in the text "fooo" and it matched correctly.

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