开发者

Javascript combining a reg expression and string

开发者 https://www.devze.com 2023-01-08 23:37 出处:网络
I have a string which contains a nonvariable part, a variable numnber and another nonvariable part. I want to user replace(), to change onl开发者_StackOverflow中文版y the variable part into a value a

I have a string which contains a nonvariable part, a variable numnber and another nonvariable part. I want to user replace(), to change onl开发者_StackOverflow中文版y the variable part into a value a user chooses. I'm a noob at javascript, and even a bigger noob in reg expressions, so sorry if this is something trivial.

Anyway, i have a string like this:

"first nonvar part: "+any_integer+"last nonvar part".

i'd like to use regexp to replace any_integer.

Can i somehow combine string and regular expression matching to match the string by it's non variably parts with an unknown number in between?

So i can use:

replace("first nonvar part: "+any_number+"last nonvar part","first nonvar part: "+user_input+"last nonvar part")

or something similar.

Many thanks


If the nonvariant parts of the string doesn't contain digits, you can just specify the digits in the expression:

str = str.replace(/\d+/, replacement);

If you want to create the regular expression by concatenating strings, you use the Regexp constructor:

var first = "first nonvar part: ";
var last = "last nonvar part";
var re = new Regexp("^" + first + "\\d+" + last + "$");
str = str.replace(re, replacement);

Note that if the nonvariant strings contain any characters that has a special meaning in a regular expression, they need to be escaped.


var str = original.replace(/(non var)\d(non var)/​​​​​​​​​​​​​​​​​​​​​, "$1" + input + "$2");

Replace the "non vars" with your non-variables.

0

精彩评论

暂无评论...
验证码 换一张
取 消