Multiple Regex on String - javascript

How can I apply multiple regexs to a single string?
For instance, a user inputs the following into a text area:
red bird
blue cat
black dog
and I want to replace each carriage return with a comma and each space with an underscore so the final string reads as red_bird,blue_cat,black_dog.
I've tried variations in syntax along the lines of the following so far:
function formatTextArea() {
var textString = document.getElementById('userinput').value;
var formatText = textString.replace(
new RegExp( "\\n", "g" ),",",
new RegExp( "\\s", "g"),"_");
alert(formatText);
}

You can chain the replacements. Every application of the replace method retuns a string, so on that string you can apply replace again. Like:
function formatTextArea() {
var textString = document.getElementById('userinput').value;
var formatText =
textString.replace(/\n/g,",")
.replace(/\s/g,"_");
alert(formatText);
}
There's no need for all these new Regular Expression Objects by the way. Use Regular Expression literals (like /\n/g in the above).
Alternatively you can use a lambda for the replacement
const str = `red bird
blue cat
black dog`;
console.log(str.replace(/[\n\s]/g, a => /\n/.test(a) ? "," : "_"));

formatText = textString.replace(/\n/g,',').replace(/\s/g,'_');

As others have mentioned, chaining is good enough for something as simple as what you're asking. However, if you want this to be more dynamic, you can use a replacer function as the second argument:
function formatTextArea() {
var textString = document.getElementById('userinput').value;
var formatText = textString.replace(/\n|\s/g, function ($0) {
if ($0 === "\n")
return ",";
else if ($0 === " ")
return "_";
}
alert(formatText);
}
Using a replacer function will allow you to be dynamic without having to chain together calls to replace(). It may also be marginally faster (regex parser is invoked only once). Be aware that \s will match more than just the space character, though :-) For the purposes of your question, this would be good enough:
var formatText = textString.replace(/\n|\s/g, function ($0) {
return $0 == "\n" ? "," : "_";
}

Regexp object have their own literal notation, using forward slashes, meaning that backslashes don't have to be escaped. For example, /\n/g is equivalent to new RegExp('\\n','g').
function formatTextArea()
{
var textString = document.getElementById('userinput').value;
textString = textString.replace(/\n/g,",").replace(/\s/g,"_");
alert(textString);
}

var textString = "red blue\nhack bye\ntest rt\n";
var formatText = textString.replace(new RegExp( "\\n", "g" ),",").replace(new RegExp( "\\s", "g"),"_");
alert(formatText);

Include http://phpjs.org/functions/str_replace:527 and then
input = str_replace("\\n", ',', input);
input = str_replace(' ', '_', input);

Related

How to put a variable in my JS regular expression? [duplicate]

I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.
The pattern is (value is the variable):
/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
I escaped the backslashes:
var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "" + value + ""));
But this seem not to be right, I logged the pattern and its exactly what it should be.
Any ideas?
To create the regex from a string, you have to use JavaScript's RegExp object.
If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.
If you are trying to use a variable value in the expression, you must use the RegExp "constructor".
var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:
str = "1x";
var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
inv=inv.replace(regex, "");
You don't need the " to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
Using string variable(s) content as part of a more complex composed regex expression (es6|ts)
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps

Live replacement for regular expressions with Javascript

I'm writing a code for live replacement of specific words in a text field as the user types.
I'm using regex and javascript:
The first array has the regular expressions to be found, and the second array has the words that should replace any them.
source = new Array(/\srsrs\s/,/\sñ\s/,/\snaum\s/,/\svc\s/,/\scd\s/,/\sOq\s/,/\soke\s/,/\so\sq\s/,
/\soque\s/,/\soqe\s/,/\spq\s/,/\sq\s/,/\sp\/\s/g,/\spra\s/,/\sp\s/,/\stbm\s/,
/\stb\s/,/\std\s/,/\sblz\s/,/\saki\s/,/\svlw\s/,/\smara\s/,/\sqlq\s/,/\sqq\s/,
/\srpz\s/,/\smsm\s/,/\smto\s/,/\smtu\s/,/\sqro\s/,/\sqdo\s/,/\sqd\s/,/\sqnd\s/,
/\sqto\s/,/\sqm\s/,/\sjah\s/, /\sc\/\s/,/\scmg\s/,/\s\+\sou\s\-\s/,/\sflw\s/,
/\sxau\s/,/\sto\s/,/\sta\s/);
after = new Array("risos","não","não","você","cadê","o que","o que","o que","o que","o que","porque",
"que","para","para","para","também","também","tudo","beleza","aqui","valeu","maravilhoso",
"qualquer","qualquer","rapaz","mesmo","muito","muito","quero","quando","quando","quando",
"quanto","quem","Já","com","comego","mais ou menos","falow","tchau","estou","está");
This is the function that does the replacement:
function replacement(){
for(i=0; i<source.length; i++){
newtext = " "+document.getElementById("translation").value+" ";
console.log(newtext);
if(myregex = newtext.match(source[i])){
newafter = after[i];
rafael = myregex+" ";
document.getElementById("translation").value = document.getElementById("translation").value.replace(rafael, newafter);
}
}
}
My problem is every time the function is called to replace an expression with only one letter, the replacement is being made on the first occurrence of that letter, even within a word. I thought looking for that letter with \s before and after would solve it, but it didn't.
If you're looking only to match a word, you should put \b before and after (word boundary). This will ensure that you don't match parts of words. Also note that you are corrupting your regex by concatenating a string. Try this instead:
var in = document.getElementById("translation").value;
if( in.charAt(in.length-1) == " ") { // user has just finished typing a word
// this avoids interrupting the word being typed
var l = source.length, i;
for( i=0; i<l; i++) in = in.replace(source[i],after[i]);
document.getElementById("translation").value = in;
}
You need to add a g (global) modified to regexes so that it will replace all occurrences and use \b instead of \s to mark word boundaries.
source = new Array(/\brsrs\b/g,/\bñ\b/g, etc
On a side note, since all your regexes follow the same pattern it might be easier to just do:
source = new Array( 'rsr', 'ñ', 'naum', etc );
if( myregex = newtext.match( new Regexp( "\b"+source[i]+"\b", 'g' ) ) ) {
...
If by "live replacement" you mean calling function replacement at each keystroke then \b at the end will not help you, you should indeed use \s. However in your replacement function your are adding a space to the text field value so your single character words are triggering the replacement.
Here is my refactoring of your code :
(function () { // wrap in immediate function to hide local variables
source = [ [/\brsrs\s$/, "risos"], // place reg exp and replacement next to each other
[/\b(ñ|naum)\s$/, "não"], // note combined regexps
[/\bvc\s$/, "você"]
// ...
]; // not also use of array literals in place of new Array
document.getElementById ("translation"​​​​​​​).addEventListener ('keyup', function (ev) {
var t = this.value // fetch text area value
, m
, i = source.length;
while (i--) // for each possible match
if ((m = t.match(source[i][0]))) { // does this one match ?
// replace match : first remove the match string (m[0]) from the end of
// the text string, then add the replacement word followed by a space
this.value = t.slice (0, -m[0].length) + source[i][1] + ' ';
return; // done
}
}, false);
}) ();​
And the fiddle is : http://jsfiddle.net/jFYuV
In a somewhat different style, you could create a function that encapsulated the list of substitutions:
var substitutions = {
"rsrs": "risos",
"ñ": "não",
"naum": "não",
"vc": "você",
// ...
};
var createSubstitutionFunction = function(subs) {
var keys = [];
for (var key in subs) {
if (subs.hasOwnProperty(key)) {
keys[keys.length] = key;
}
}
var regex = new RegExp("\\b" + keys.join("\\b|\\b") + "\\b", "g");
return function(text) {
return text.replace(regex, function(match) {
return subs[match];
});
};
};
var replacer = createSubstitutionFunction(substitutions);
You would use it like this:
replacer("Some text with rsrs and naum and more rsrs and vc")
// ==> "Some text with risos and não and more risos and você"

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

I want to use str_replace or its similar alternative to replace some text in JavaScript.
var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write(new_text);
should give
this is some sample text that i dont want to replace
If you are going to regex, what are the performance implications in
comparison to the built in replacement methods.
You would use the replace method:
text = text.replace('old', 'new');
The first argument is what you're looking for, obviously. It can also accept regular expressions.
Just remember that it does not change the original string. It only returns the new value.
More simply:
city_name=city_name.replace(/ /gi,'_');
Replaces all spaces with '_'!
All these methods don't modify original value, returns new strings.
var city_name = 'Some text with spaces';
Replaces 1st space with _
city_name.replace(' ', '_'); // Returns: "Some_text with spaces" (replaced only 1st match)
Replaces all spaces with _ using regex. If you need to use regex, then i recommend testing it with https://regex101.com/
city_name.replace(/ /gi,'_'); // Returns: Some_text_with_spaces
Replaces all spaces with _ without regex. Functional way.
city_name.split(' ').join('_'); // Returns: Some_text_with_spaces
You should write something like that :
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
The code that others are giving you only replace one occurrence, while using regular expressions replaces them all (like #sorgit said). To replace all the "want" with "not want", us this code:
var text = "this is some sample text that i want to replace";
var new_text = text.replace(/want/g, "dont want");
document.write(new_text);
The variable "new_text" will result in being "this is some sample text that i dont want to replace".
To get a quick guide to regular expressions, go here:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
To learn more about str.replace(), go here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
Good luck!
that function replaces only one occurrence.. if you need to replace
multiple occurrences you should try this function:
http://phpjs.org/functions/str_replace:527
Not necessarily.
see the Hans Kesting answer:
city_name = city_name.replace(/ /gi,'_');
Using regex for string replacement is significantly slower than using a string replace.
As demonstrated on JSPerf, you can have different levels of efficiency for creating a regex, but all of them are significantly slower than a simple string replace. The regex is slower because:
Fixed-string matches don't have backtracking, compilation steps, ranges, character classes, or a host of other features that slow down the regular expression engine. There are certainly ways to optimize regex matches, but I think it's unlikely to beat indexing into a string in the common case.
For a simple test run on the JS perf page, I've documented some of the results:
<script>
// Setup
var startString = "xxxxxxxxxabcxxxxxxabcxx";
var endStringRegEx = undefined;
var endStringString = undefined;
var endStringRegExNewStr = undefined;
var endStringRegExNew = undefined;
var endStringStoredRegEx = undefined;
var re = new RegExp("abc", "g");
</script>
<script>
// Tests
endStringRegEx = startString.replace(/abc/g, "def") // Regex
endStringString = startString.replace("abc", "def", "g") // String
endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String
endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp
endStringStoredRegEx = startString.replace(re, "def") // saved regex
</script>
The results for Chrome 68 are as follows:
String replace: 9,936,093 operations/sec
Saved regex: 5,725,506 operations/sec
Regex: 5,529,504 operations/sec
New Regex String: 3,571,180 operations/sec
New Regex: 3,224,919 operations/sec
From the sake of completeness of this answer (borrowing from the comments), it's worth mentioning that .replace only replaces the first instance of the matched character. Its only possible to replace all instances with //g. The performance trade off and code elegance could be argued to be worse if replacing multiple instances name.replace(' ', '_').replace(' ', '_').replace(' ', '_'); or worse while (name.includes(' ')) { name = name.replace(' ', '_') }
var new_text = text.replace("want", "dont want");
hm.. Did you check replace() ?
Your code will look like this
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
JavaScript has replace() method of String object for replacing substrings. This method can have two arguments. The first argument can be a string or a regular expression pattern (regExp object) and the second argument can be a string or a function. An example of replace() method having both string arguments is shown below.
var text = 'one, two, three, one, five, one';
var new_text = text.replace('one', 'ten');
console.log(new_text) //ten, two, three, one, five, one
Note that if the first argument is the string, only the first occurrence of the substring is replaced as in the example above. To replace all occurrences of the substring you need to provide a regular expression with a g (global) flag. If you do not provide the global flag, only the first occurrence of the substring will be replaced even if you provide the regular expression as the first argument. So let's replace all occurrences of one in the above example.
var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, 'ten');
console.log(new_text) //ten, two, three, ten, five, ten
Note that you do not wrap the regular expression pattern in quotes which will make it a string not a regExp object. To do a case insensitive replacement you need to provide additional flag i which makes the pattern case-insensitive. In that case the above regular expression will be /one/gi. Notice the i flag added here.
If the second argument has a function and if there is a match the function is passed with three arguments. The arguments the function gets are the match, position of the match and the original text. You need to return what that match should be replaced with. For example,
var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, function(match, pos, text){
return 'ten';
});
console.log(new_text) //ten, two, three, ten, five, ten
You can have more control over the replacement text using a function as the second argument.
In JavaScript, you call the replace method on the String object, e.g. "this is some sample text that i want to replace".replace("want", "dont want"), which will return the replaced string.
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want"); // new_text now stores the replaced string, leaving the original untouched
You can use
text.replace('old', 'new')
And to change multiple values in one string at once, for example to change # to string v and _ to string w:
text.replace(/#|_/g,function(match) {return (match=="#")? v: w;});
There are already multiple answers using str.replace() (which is fair enough for this question) and regex but you can use combination of str.split() and join() together which is faster than str.replace() and regex.
Below is working example:
var text = "this is some sample text that i want to replace";
console.log(text.split("want").join("dont want"));
If you really want a equivalent to PHP's str_replace you can use Locutus. PHP's version of str_replace support more option then what the JavaScript String.prototype.replace supports.
For example tags:
//PHP
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
//JS with Locutus
var $bodytag = str_replace(['{body}', 'black', '<body text='{body}'>')
or array's
//PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
//JS with Locutus
var $vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
var $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
Also this doesn't use regex instead it uses for loops. If you not want to use regex but want simple string replace you can use something like this ( based on Locutus )
function str_replace (search, replace, subject) {
var i = 0
var j = 0
var temp = ''
var repl = ''
var sl = 0
var fl = 0
var f = [].concat(search)
var r = [].concat(replace)
var s = subject
s = [].concat(s)
for (i = 0, sl = s.length; i < sl; i++) {
if (s[i] === '') {
continue
}
for (j = 0, fl = f.length; j < fl; j++) {
temp = s[i] + ''
repl = r[0]
s[i] = (temp).split(f[j]).join(repl)
if (typeof countObj !== 'undefined') {
countObj.value += ((temp.split(f[j])).length - 1)
}
}
}
return s[0]
}
var text = "this is some sample text that i want to replace";
var new_text = str_replace ("want", "dont want", text)
document.write(new_text)
for more info see the source code https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js
You have the following options:
Replace the first occurrence
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace('want', 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well"
console.log(new_text)
Replace all occurrences - case sensitive
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/g, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well
console.log(new_text)
Replace all occurrences - case insensitive
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/gi, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i dont want to replace as well
console.log(new_text)
More info -> here
In Javascript, replace function available to replace sub-string from given string with new one.
Use:
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
console.log(new_text);
You can even use regular expression with this function. For example, if want to replace all occurrences of , with ..
var text = "123,123,123";
var new_text = text.replace(/,/g, ".");
console.log(new_text);
Here g modifier used to match globally all available matches.
Method to replace substring in a sentence using React:
const replace_in_javascript = (oldSubStr, newSubStr, sentence) => {
let newStr = "";
let i = 0;
sentence.split(" ").forEach(obj => {
if (obj.toUpperCase() === oldSubStr.toUpperCase()) {
newStr = i === 0 ? newSubStr : newStr + " " + newSubStr;
i = i + 1;
} else {
newStr = i === 0 ? obj : newStr + " " + obj;
i = i + 1;
}
});
return newStr;
};
RunMethodHere
If you don't want to use regex then you can use this function which will replace all in a string
Source Code:
function ReplaceAll(mystring, search_word, replace_with)
{
while (mystring.includes(search_word))
{
mystring = mystring.replace(search_word, replace_with);
}
return mystring;
}
How to use:
var mystring = ReplaceAll("Test Test", "Test", "Hello");
Use JS String.prototype.replace first argument should be Regex pattern or String and Second argument should be a String or function.
str.replace(regexp|substr, newSubStr|function);
Ex:
var str = 'this is some sample text that i want to replace';
var newstr = str.replace(/want/i, "dont't want");
document.write(newstr); // this is some sample text that i don't want to replace
ES2021 / ES12
String.prototype.replaceAll()
is trying to bring the full replacement option even when the input pattern is a string.
const str = "Backbencher sits at the Back";
const newStr = str.replaceAll("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Front"
1- String.prototype.replace()
We can do a full **replacement** only if we supply the pattern as a regular expression.
const str = "Backbencher sits at the Back";
const newStr = str.replace(/Back/g, "Front");
console.log(newStr); // "Frontbencher sits at the Front"
If the input pattern is a string, replace() method only replaces the first occurrence.
const str = "Backbencher sits at the Back";
const newStr = str.replace("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Back"
2- You can use split and join
const str = "Backbencher sits at the Back";
const newStr = str.split("Back").join("Front");
console.log(newStr); // "Frontbencher sits at the Front"
function str_replace($old, $new, $text)
{
return ($text+"").split($old).join($new);
}
You do not need additional libraries.
In ECMAScript 2021, you can use replaceAll can be used.
const str = "string1 string1 string1"
const newStr = str.replaceAll("string1", "string2");
console.log(newStr)
// "string2 string2 string2"
simplest form as below
if you need to replace only first occurrence
var newString = oldStr.replace('want', 'dont want');
if you want ot repalce all occurenace
var newString = oldStr.replace(want/g, 'dont want');
Added a method replace_in_javascript which will satisfy your requirement. Also found that you are writing a string "new_text" in document.write() which is supposed to refer to a variable new_text.
let replace_in_javascript= (replaceble, replaceTo, text) => {
return text.replace(replaceble, replaceTo)
}
var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write(new_text);

Javascript: highlight substring keeping original case but searching in case insensitive mode

I'm trying to write a "suggestion search box" and I cannot find a solution that allows to highlight a substring with javascript keeping the original case.
For example if I search for "ca" I search server side in a case insensitive mode and I have the following results:
Calculator
calendar
ESCAPE
I would like to view the search string in all the previous words, so the result should be:
Calculator
calendar
ESCAPE
I tried with the following code:
var reg = new RegExp(querystr, 'gi');
var final_str = 'foo ' + result.replace(reg, '<b>'+querystr+'</b>');
$('#'+id).html(final_str);
But obviously in this way I loose the original case!
Is there a way to solve this problem?
Use a function for the second argument for .replace() that returns the actual matched string with the concatenated tags.
Try it out: http://jsfiddle.net/4sGLL/
reg = new RegExp(querystr, 'gi');
// The str parameter references the matched string
// --------------------------------------v
final_str = 'foo ' + result.replace(reg, function(str) {return '<b>'+str+'</b>'});
$('#' + id).html(final_str);​
JSFiddle Example with Input: https://jsfiddle.net/pawmbude/
ES6 version
const highlight = (needle, haystack) =>
haystack.replace(
new RegExp(needle, 'gi'),
(str) => `<strong>${str}</strong>`
);
nice results with
function str_highlight_text(string, str_to_highlight){
var reg = new RegExp(str_to_highlight, 'gi');
return string.replace(reg, function(str) {return '<span style="background-color:#ffbf00;color:#fff;"><b>'+str+'</b></span>'});
}
and easier to remember...
thx to user113716: https://stackoverflow.com/a/3294644/2065594
While the other answers so far seem simple, they can't be really used in many real world cases as they don't handle proper text HTML escaping and RegExp escaping. If you want to highlight every possible snippet, while escaping the text properly, a function like that would return all elements you should add to your suggestions box:
function highlightLabel(label, term) {
if (!term) return [ document.createTextNode(label) ]
const regex = new RegExp(term.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi')
const result = []
let left, match, right = label
while (match = right.match(regex)) {
const m = match[0], hl = document.createElement('b'), i = match.index
hl.innerText = m
left = right.slice(0, i)
right = right.slice(i + m.length)
result.push(document.createTextNode(left), hl)
if (!right.length) return result
}
result.push(document.createTextNode(right))
return result
}
string.replace fails in the general case. If you use .innerHTML, replace can replace matches in tags (like a tags). If you use .innerText or .textContent, it will remove any tags there were previously in the html. More than that, in both cases it damages your html if you want to remove the highlighting.
The true answer is mark.js (https://markjs.io/). I just found this - it is what I have been searching for for such a long time. It does just what you want it to.
I do the exact same thing.
You need to make a copy.
I store in the db a copy of the real string, in all lower case.
Then I search using a lower case version of the query string or do a case insensitive regexp.
Then use the resulting found start index in the main string, plus the length of the query string, to highlight the query string within the result.
You can not use the query string in the result since its case is not determinate. You need to highlight a portion of the original string.
.match() performs case insensitive matching and returns an array of the matches with case intact.
var matches = str.match(queryString),
startHere = 0,
nextMatch,
resultStr ='',
qLength = queryString.length;
for (var match in matches) {
nextMatch = str.substr(startHere).indexOf(match);
resultStr = resultStr + str.substr(startHere, nextMatch) + '<b>' + match + '</b>';
startHere = nextMatch + qLength;
}
I have found a easiest way to achieve it. JavaScript regular expression remembers the string it matched. This feature can be used here.
I have modified the code a bit.
reg = new RegExp("("+querystr.trim()+")", 'gi');
final_str = 'foo ' + result.replace(reg, "<b>&1</b>");
$('#'+id).html(final_str);
Highlight search term and anchoring to first occurence - Start
function highlightSearchText(searchText) {
var innerHTML = document.documentElement.innerHTML;
var replaceString = '<mark>'+searchText+'</mark>';
var newInnerHtml = this.replaceAll(innerHTML, searchText, replaceString);
document.documentElement.innerHTML = newInnerHtml;
var elmnt = document.documentElement.getElementsByTagName('mark')[0]
elmnt.scrollIntoView();
}
function replaceAll(str, querystr, replace) {
var reg = new RegExp(querystr, 'gi');
var final_str = str.replace(reg, function(str) {return '<mark>'+str+'</mark>'});
return final_str
}
Highlight search term and anchoring to first occurence - End

Split String at specific character

I have the following code:
var string = "word1;word2;word3,word4,word5,word6.word7";
function ends_with(string, character) {
var regexp = new RegExp('\\w+' + character, 'g');
var matches = string.match(regexp);
var replacer = new RegExp(character + '$');
return matches.map(function(ee) {
return ee.replace(replacer, '');
});
}
// ends_with(string, ';') => ["word1", "word2"]
The function takes no regard to whitespace. For example if you input
ends_with('Jonas Sand,', ',')
the output will be Sand. Need help on making the function work with words that has whitespace.
You can use your separator within split and take all except the last part with slice:
function ends_with(string, character) {
return string.split(character).slice(0, -1);
}
\w matches word characters, use [^x] instead, where x is your character. This matches everything but your character.
So the first line in your function becomes
var regexp = new RegExp('[^' + character + "]+" + character, 'g');
on the other hand, if you want to match words separated by white space, use
var regexp = new RegExp('(\\w|\\s)+" + character, 'g');
PS: but isn't there a String#split function in javascript?
Try using '[\\w\\s]+' instead of '\\w+' to include whitespace.
Try the following:
var string = "word1;w ord2;word3,word4,word5,word6.word7";
function ends_with(string, character) {
var regexp = new RegExp('.+' + character, 'g');
var matches = string.match(regexp);
var replacer = new RegExp(character + '$');
return matches.map(function(ee) {
return ee.replace(replacer, '');
});
}

Categories

Resources